【发布时间】:2019-08-29 17:46:31
【问题描述】:
我写了一个函数来查找特定范围内具有特定值的单元格。但我不断收到“需要对象”错误:如果 rng 为空。
如果我将函数参数(搜索值)类型设置为字符串,则不会出现此错误,仅当函数参数(搜索值)类型为变体时才会出现此错误。
这是我的代码:
Function TgtCell(SearchRange As Range, Optional SearchValue As Variant) As Range
For Each Rng In SearchRange
If IsMissing(SearchValue) Then
If Rng Is Empty Then 'this is the line with the error
TgtCell = Rng
Exit For
End If
Else
If Rng.Value = SearchValue Then
Set TgtCell = Rng
Exit For
End If
End If
Next
End Function
下面是我的测试代码:
Sub test1()
Set Rng = TgtCell(Range([a1:a14], Cells(Rows.Count, 1)))
Rng.Select
End Sub
请帮助我理解为什么会这样。
【问题讨论】: