VBA:从函数返回Range.Find()结果

3

我需要将Range.Find()封装在一个函数中,因此我有以下代码(R1、C1等均为已定义的常量):

Function FindData(FindWhat As Variant) As Range
    Dim TheR As Range
    Set TheR = Range(Cells(R1, C1), Cells(R2, C2)).Find(FindWhat, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    FindData = TheR
End Function

我正在传递一个字符串,所以调用是例如:

Set FirstCell = Call FindData("MyValue")

VBA在该行FindData = TheR出现错误,提示信息为Object variable or With block variable not set。我尝试添加了以下if块:

If (TheR Is Nothing) Then
    FindData = Nothing
Else
    FindData = TheR
End If

但这并没有什么区别。我该如何返回Find()函数给我的值?

1个回答

3
对于对象变量,即使在函数中,您也需要添加Set关键字! ;)
因此,只需在末尾添加它:
Function FindData(FindWhat As Variant) As Range
    Dim TheR As Range
    Set TheR = Range(Cells(R1, C1), Cells(R2, C2)).Find(FindWhat, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    Set FindData = TheR
End Function

当您使用Call时,您将无法从函数中获得输出,因此您需要使用括号:

Set FirstCell = FindData("MyValue")

哦,嗯!我应该意识到那个问题的!非常感谢 :) - skiaddict1
@skiaddict1:当我开始使用对象函数时,我也遇到了同样的问题!;) 如果您的问题已解决,请接受答案;) - R3uK
1
你可以忽略 Dim TheR As RangeSet FindData = TheR,并直接使用 Set FindData= Range(Cells(R1, C1), Cells(R2, C2)).Find(FindWhat, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext) - user3598756

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