如何使用Excel VBA中的“查找”功能修复错误

时间:2013-04-18 20:27:15

标签: excel excel-vba vba

我试图从另一张表中搜索一个值而不是使用.FIND函数

Private Function Search(rng As Range, FindString As String) As Range
    With rng
        Set Search = .Find(what:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        lookat:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
     End With

有趣的是,如果我进入

Search(Range("'DataSheet'!A1:Z1000"),"STARTING") 

有效。当我尝试

 SearchString = "'" & Selected_sheet &"'!A1:Z1000"

它不起作用Selected_sheet只是工作表的名称(在这种情况下,它是“DataSheet”)。使用

Search(Range(SearchString ),"STARTING") 

Error: RUN-TIME ERROR '91'
Object variable or With Block Varibale Not Set

实际问题可能是什么?

1 个答案:

答案 0 :(得分:1)

你的方法不正确,但我建议不要那样传递你的范围。

使用此

Search(Sheets("DataSheet").Range("A1:Z1000"),"STARTING")

Selected_sheet = "DataSheet"
Search(Sheets(Selected_sheet).Range("A1:Z1000"),"STARTING")

BTW代码中的Range(SearchString)没有任何问题。它应该工作。你怎么称Search?希望这样吗?

Dim Ret As Range '<~~~

Selected_sheet = "DataSheet"
SearchString = "'" & Selected_sheet & "'!A1:Z1000"
Set Ret = Search(Range(SearchString), "STARTING")

原因:该函数返回Range,因此您不能在没有Set Ret = ...的情况下调用它,其中Ret再次声明为Range

修改

如果Search函数未返回范围并尝试使用Ret,则也会出现该错误。见这个例子。

Dim Ret As Range

Selected_sheet = "DataSheet"
SearchString = "'" & Selected_sheet & "'!A1:Z1000"
Set Ret = Search(Range(SearchString), "STARTING")

'<~~ This will give you RUN-TIME ERROR '91' if "STARTING" is not found
Debug.Print Ret.Address

那么我们如何处理这个

试试这个

Dim Ret As Range

Selected_sheet = "DataSheet"
SearchString = "'" & Selected_sheet & "'!A1:Z1000"
Set Ret = Search(Range(SearchString), "STARTING")

If Not Ret Is Nothing Then
    Debug.Print Ret.Address
Else
    Debug.Print "Search Didn't return any results"
End If