.Find() 运行-Time error '91': Object variable or with block variable not set

.Find() Run-Time error '91': Object variable or with block variable not set

我知道其他问题也有同样的错误,但它与我所拥有的相去甚远。我试图通过循环(lab 值更改)多次找到可以在 B 列中找到变量 lab 值的行,它第一次有效,但第二次出现此错误。

For Each lab In arr    
    NFD = el & " " & Sheets("Sheet1").Cells(1, 3).value
    If SheetExists(NFD) Then

       Worksheets(NFD).Activate

       Dim FindRow As Range
       Dim FindRowNumber As Long
       Set FindRow = Sheets(NFD).Range("B:B").Find(What:=lab, LookIn:=xlValues)
       FindRowNumber = FindRow.Row 'error on this line

        MsgBox FindRowNumber

    End If
Next 

EDIT1:如果有人感兴趣,这是工作代码:

For Each lab In arr
                If lab <> "" Then
                    lab = Trim(lab)
                        'Find element Sheet
                        NFD = el & " " & Sheets("Sheet1").Cells(1, 3).value
                            If SheetExists(NFD) Then    
                                'Find lab number row in colunm B
                              Set FindRow = Sheets(NFD).Range("B:B").Find(What:=lab, LookIn:=xlValues)

                               If FindRow Is Nothing Then
                                 Debug.Print "Nothing Found"
                               Else
                                  FindRowNumber = FindRow.Row

                               End If

                             End If

                End If

Next

您可能需要检查是否找到任何内容。如果项目不存在,FindRow 将是 'Nothing'。

If FindRow Is Nothing Then
    MsgBox "Nothing Found"
    'you can set FindRowNumber to something here if you want, like 0 or -1
Else
    FindRowNumber = FindRow.Row
    MsgBox FindRowNumber
End If

评论问题后编辑 我的测试代码是:

Sub test()
    Dim arr(0 To 2) As String
    Dim lab As Variant
    Dim FindRow As Range
    Dim FindRowNumber As Long

    arr(0) = "aaa"
    arr(1) = "bbb"
    arr(2) = "ccc"

    For Each lab In arr
        Set FindRow = Sheets("Sheet1").Range("B:B").Find(What:=lab, LookIn:=xlValues)

        If FindRow Is Nothing Then
            Debug.Print "Nothing Found"
            'you can set FindRowNumber to something here if you want, like 0 or -1
        Else
            FindRowNumber = FindRow.Row
            Debug.Print FindRowNumber
        End If
    Next
End Sub

我在单元格 B1、B2 和 B3 中分别有 'aaa'、'bbb' 和 'ccc',它们都按预期工作,在调试控制台。