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

时间:2015-03-15 21:55:21

标签: excel vba find nothing

我正在尝试在列表中找到一个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。 “编译错误;无效使用对象”。不知道该怎么做。

2 个答案:

答案 0 :(得分:6)

要检查range对象,您需要使用is代替=

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

<强>解释

Taken from Allen Browne

Nothing是对象变量的未初始化状态。对象不能是一个简单的变量,如数字或字符串,因此它永远不能是0或&#34;&#34;。它必须是一个更全面的结构(文本框,表单,记录集,querydef,...)

由于它不是一个简单的值,你无法测试它是否等于某个东西。 VBA有一个Is关键字,您可以使用。

答案 1 :(得分:-3)

这解决了吗?如果是,请选中已解决的复选框。

查找匹配键值和地址的另一种方法是使用匹配函数,该函数返回匹配键值的行(如果找到)。如果找不到,则返回#N / A.然后,您可以使用if(ISNA(Rangeaddress))...

循环遍历列