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

dws*_*ein 4 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
Run Code Online (Sandbox Code Playgroud)

当我运行时,在高亮显示单词test_stuff()的行中出现函数错误。“编译错误;无效使用对象”。不知道该怎么办。If found1 = Nothing ThenNothing

tos*_*pig 9

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

If found1 Is Nothing Then
    MsgBox "nothing"
Else
    MsgBox found1.AddressLocal
End If
Run Code Online (Sandbox Code Playgroud)

说明:

取自艾伦·布朗(Allen Browne)

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

由于它不是一个简单的值,因此无法测试它是否等于某个值。VBA具有Is您使用的关键字。