VBA SpecialCells代码在家用PC上有效,但在工作PC上无效

时间:2020-08-31 13:19:26

标签: excel vba

我编写宏来自动执行工作流程。我当前的宏必须选择过滤数据的第一可见行。我在同一版本的Excel(16)上在家测试了此代码,并且工作正常。但是,当我在工作时尝试它时,它出现了[运行时错误代码'1004':无法获取Range类的SpecialCells属性]。

我已经检查以确保书籍之间的格式相同。测试手册的数据大小大于工作手册的数据大小。由于该代码可在同一版本的Excel上正常运行,因此我不确定是什么原因引起了差异。这是我正在使用的代码。

Sub First_Visible_Cell()

    With Worksheets("Items").AutoFilter.Range
        Range("A" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
    End With

End Sub

1 个答案:

答案 0 :(得分:0)

您的Range对象未使用With语句,因为它不是以点开头。

所以这个

With Worksheets("Items").AutoFilter.Range
    Range("A" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
End With

实际上与

相同
With Worksheets("Items").AutoFilter.Range
    ActiveSheet.Range("A" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
End With

您可能打算这样做

With Worksheets("Items").AutoFilter.Range
    Worksheets("Items").Range("A" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
End With

还请注意,如果未设置AutoFilter,它将引发错误,并且.Offset(1, 0)中也没有可见的单元格,则也会引发错误:

Dim wsItems As Worksheet
Set wsItems = Worksheets("Items")

With wsItems.AutoFilter.Range
    Dim VisibleCells As Range
    On Error Resume Next 'hide errors if they occur
    Set VisibleCells = .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1) 'throws error if no visible cells
    On Error Goto 0 're-enable error reporting!

    If Not VisibleCells Is Nothing Then
        wsItems.Range("A" & VisibleCells.Row).Select
    Else
        MsgBox "No Visible Cells"
    End If
End With
相关问题