VBA收到运行时错误91,但不是每次都出现?

时间:2020-06-03 10:36:03

标签: excel vba

当我跳过显示问题的子目录时,会发生这种情况:

我似乎无法解决此问题,因为我多次使用了此子代码段,因此效果很好。


Private Sub UserForm_Initialize()

Sheets("Data").Range("A:T").AutoFilter Field:=18
Sheets("Data").Range("A:T").AutoFilter Field:=18, Criteria1:="FALSCH"
    ActiveWorkbook.Worksheets("Data").AutoFilter.Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Data").AutoFilter.Sort.SortFields.Add Key:=Range( _
        "I:I"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Data").AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Dim lRow As Long
Dim lCol As Long

    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

1 个答案:

答案 0 :(得分:3)

结构应如下所示:

Dim ws As Worksheet
Set ws = Worksheets("Data")

Dim FoundAt As Range
Set FoundAt = ws.Cells.Find(What:="*", _
                After:=ws.Range("A1"), _
                LookAt:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False)

If Not FoundAt Is Nothing Then
    Dim lRow As Long
    lRow = FoundAt.Row

    'your other code here …
Else
    MsgBox "Find failed!"
End If

首先尝试使用ws.Cells.Find查找单元格并将其引用到范围变量FoundAt,以便您可以使用If Not FoundAt Is Nothing Then测试是否找到了单元格,因为{{1} }仅在找到单元格的情况下存在。如果您什么都没找到,那么什么也没有行(显然)。