在excel vba中查找`find`方法是否返回`nothing` [英] find if `find` method returns `nothing` in excel vba
问题描述
我正在尝试在列表中找到一个 id 并获取它的地址,但如果没有找到,也要处理一种情况.
I'm trying to find an id in a list and get it's address, but also deal with a situation if nothing is found.
这是我所拥有的:
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
.编译错误;对象的无效使用".不知道该怎么办.
When I run test_stuff()
I get an error in the function in the line If found1 = Nothing Then
with the word Nothing
highlighted. "Compile error; Invalid Use of Object". Not sure what to do.
推荐答案
要检查 range
对象,您需要使用 is
而不是 =
:
To check the range
object you need to use is
instead of =
:
If found1 Is Nothing Then
MsgBox "nothing"
Else
MsgBox found1.AddressLocal
End If
说明:
Nothing
是对象变量的未初始化状态.一个对象不能是一个简单的变量,比如一个数字或一个字符串,所以它永远不能是 0 或".它必须是更全面的结构(文本框、表单、记录集、querydef ......)
Nothing
is the uninitialized state of an object variable. An object cannot be a simple variable such as a number or a string, so it can never be 0 or "". It must be a more comprehensive structure (a text box, form, recordset, querydef, ...)
由于它不是一个简单的值,因此您无法测试它是否等于某个值.VBA 有一个您使用的 Is
关键字.
Since it is not a simple value, you cannot test if it is equal to something. VBA has an Is
keyword that you use.
这篇关于在excel vba中查找`find`方法是否返回`nothing`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!