excel - 查找 `find` 方法是否在 Excel VBA 中返回 `nothing`

标签 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突出显示。 “编译错误;对象使用无效”。不知道该怎么办。

最佳答案

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

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

说明:

Taken from Allen Browne

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

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

关于excel - 查找 `find` 方法是否在 Excel VBA 中返回 `nothing`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29066633/

相关文章:

excel - 当我不知道上限值时如何在excel vba中使用 'ReDim Preserve'

excel - Excel 中的天数跟踪器

Excel - 清除特定单元格按钮

unix - 如何在unix "./"中去除前导 "find"?

javascript - Find() 函数返回未定义 - Mongoose 和 Node.js

python - 如何在python中检查上传的文件是csv还是xls?

VBA 日期格式 - 月/日/年

vba - 宏仅将值从一张纸复制到另一张纸

excel - 在 VBA 中输入公式数组的问题

bash - 将 3 个单独的命令合并为一个,用于重新编码视频、提取缩略图、删除原始视频并在子目录中重命名新视频