在excel vba中查找`find`方法是否返回`Nothing`

我试图在列表中find一个id并得到它的地址,但是如果没有发现,也要处理一个情况。

这是我有:

Function find_in_two_ranges_two_sheets(ws1 As String, col1 As Integer) As Range Dim rows1 As Integer rows1 = Get_Rows_Generic(ws1, 1) Dim range1 As Range ' range of first search With Worksheets(ws1) Set range1 = .Range(.Cells(1, col1), .Cells(rows1, col1)) End With Dim found1 As Range Set found1 = range1.Find("test id", LookIn:=xlValues) If found1 = Nothing Then MsgBox "nothing" Else MsgBox found1.AddressLocal End If Set find_in_two_ranges_two_sheets = range1 End Function Sub test_stuff() Dim x As Range Set x = find_in_two_ranges_two_sheets("usersFullOutput.csv", 1) MsgBox x.Address End Sub 

当我运行test_stuff()我得到一个错误在函数中的行If found1 = Nothing Then与单词Nothing突出显示。 “编译错误;对象的无效使用”。 不知道该怎么办。

要检查您需要使用的range对象而不是=

 If found1 Is Nothing Then MsgBox "nothing" Else MsgBox found1.AddressLocal End If 

说明:

采取从艾伦·布朗

Nothing是对象variables的未初始化状态。 一个对象不能是一个简单的variables,如数字或string,所以它不能是0或“”。 它必须是一个更全面的结构(文本框,表单,logging集,querydef,…)

既然它不是一个简单的值,你不能testing它是否等于某个东西。 VBA有一个您使用的关键字。

这能解决吗? 如果是这样,请检查解决的checkbox。

find匹配关键字值和地址的另一种方法是使用Match函数,如果find匹配关键字值,则返回匹配关键字值的行。 如果没有find,则返回#N / A。 然后你可以循环使用if(ISNA(Rangeaddress))列…