选择每张纸上的第一个可见单元格,并在VBA中使用循环

问题描述 投票:0回答:2

我使用下面的VBA在过滤范围内选择第一个可见单元格

Sub Postioning_Option_01()
Sheet1.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
End Sub

现在,我不想只将VBA应用于Sheet1,而是要[[循环遍历所有工作表。因此,我尝试使用此VBA

Sub Postioning_Option_02() Dim b As Worksheet For Each b In Worksheets b.Select b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select Next b End Sub
[当我运行此VBA时,出现错误Object variable or With block variable not set。我需要在VBA中进行哪些更改才能使其正常工作?
excel vba
2个回答
0
投票
这将跳过没有自动过滤器的工作表:

Sub Postioning_Option_02() Dim b As Worksheet For Each b In Worksheets If b.AutoFilterMode Then b.Select b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select End If Next b End Sub


0
投票
小型自动筛选研究

[关于前4个Subs没什么特别的,但是后2个看起来更深,但是可能没有上下文。

Option Explicit Sub Positioning_Option_01() If Sheet1.AutoFilterMode Then Sheet1.AutoFilter.Range.Offset(1) _ .SpecialCells(xlCellTypeVisible).Cells(1, 2).Select Else End If End Sub Sub Postioning_Option_02() Dim b As Worksheet For Each b In ThisWorkbook.Worksheets b.Activate If b.AutoFilterMode Then b.AutoFilter.Range.Offset(1) _ .SpecialCells(xlCellTypeVisible).Cells(1, 2).Select Else End If Next End Sub Sub Positioning_Option_01_With() With Sheet1 If .AutoFilterMode Then With .AutoFilter.Range.Offset(1) _ .SpecialCells(xlCellTypeVisible).Cells(1, 2) .Select End With Else End If End With End Sub Sub Postioning_Option_02_With() Dim b As Worksheet For Each b In ThisWorkbook.Worksheets b.Activate With b If .AutoFilterMode Then With .AutoFilter.Range.Offset(1) _ .SpecialCells(xlCellTypeVisible).Cells(1, 2) .Select End With Else End If End With Next End Sub Sub Pos_Offset() With Sheet1 If .AutoFilterMode Then ' The following range refers to the range below headers containing ' data and one empty row range below data. With .AutoFilter.Range.Offset(1) ' If no match in AutoFilter, after applying "SpecialCells" ' the cell in the row below data will be selected. You can't ' tell if it is contained in "AutoFilter.Range". With .SpecialCells(xlCellTypeVisible).Cells(1, 2) .Select Debug.Print .Address, .Value End With End With Else ' AutoFilterMode is False MsgBox "AutoFilterMode is set to 'False'." End If End With End Sub Sub Pos_Actual() With Sheet1 If .AutoFilterMode Then ' The range below headers containing data. With .AutoFilter.Range With .Rows(2).Resize(.Rows.Count - 1) ' If no match in AutoFilter, after applying SpecialCells ' in the following line, the following error occurs: ' "Run-time error '1004': No cells were found." ' Therefore: On Error Resume Next With .SpecialCells(xlCellTypeVisible).Cells(1, 2) If Err.Number <> 0 Then ' The are no visible cells. MsgBox "No visible cells." Else .Select Debug.Print .Address, .Value End If On Error GoTo 0 End With End With End With Else ' AutoFilterMode is False MsgBox "AutoFilterMode is set to 'False'." End If End With End Sub

© www.soinside.com 2019 - 2024. All rights reserved.