find if `find` 方法 returns `nothing` in excel vba

find if `find` method returns `nothing` in excel vba

我试图在列表中找到一个 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 一词。 "Compile error; Invalid Use of Object"。不知道该怎么做。

要检查 range 对象,您需要使用 is 而不是 =:

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

解释:

Taken from Allen Browne

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

因为它不是一个简单的值,所以你无法测试它是否等于某物。 VBA 有一个 Is 您使用的关键字。