在Excel VBA中查找`find`方法是否返回“nothing”

7
我将尝试在列表中查找一个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 被突出显示。错误信息是“编译错误; 对象无效”。不确定该怎么办。

4
如果发现 found1 是空值,则尝试执行以下操作: - tospig
1个回答

15

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

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

解释:

引用自Allen Browne

Nothing是一个对象变量未初始化的状态。对象不能是像数字或字符串这样的简单变量,因此它永远不可能是0或""。它必须是一个更全面的结构(文本框、表单、记录集、查询定义等)。

由于它不是一个简单值,你不能测试它是否等于某个东西。VBA有一个Is关键字来使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接