我知道其他问题已经被问到同样的错误,但它没有接近我所拥有的。我试图通过循环(实验室值更改)找到可以在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
答案 0 :(得分:5)
您可能需要检查是否找到了任何内容。 FindRow将是“什么都没有”。如果项目不在那里。
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
我有&#39; aaa&#39; bbb&#39;和&#c; ccc&#39;在单元格B1,B2和B3中,它们都按预期工作,在调试控制台中打印1,2和3。