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

时间:2016-10-11 07:36:22

标签: excel vba excel-vba object

我需要在一个函数中封装Range.Find(),所以我有以下内容(R1,C1等都是已定义的consts):

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-block:

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

但它没有任何区别。如何返回Find()给我的值?

1 个答案:

答案 0 :(得分:2)

对于对象变量,您需要添加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")