search工作簿的string – 运行时错误424(需要对象)

我正在尝试使用macros来search某个string的Excel工作簿。 我想获取findstring的单元格的地址,并将其放在当前表格的第一列中。 我的代码和问题如下。

 Option Explicit Sub Find_Data() Dim datatoFind As String Dim rangeSearch As Range Dim rangeLast As Range Dim foundRange As Range Dim strFirstAddress As String Dim sheetCount As Integer Dim sheetCounter As Integer Dim currentSheet As Integer Dim foundmatrixCounter As Integer foundmatrixCounter = 2 'initialize this to the second row so the total can be placed in the first row when done 'set search range Set rangeSearch = ActiveSheet.Range("B2:X100") 'set last cell in range Set rangeLast = rangeSearch.Cells(rangeSearch.Cells.Count) currentSheet = ActiveSheet.Index datatoFind = InputBox("Please enter the value to search for") If datatoFind = "" Then Exit Sub sheetCount = ActiveWorkbook.Sheets.Count For sheetCounter = 1 To sheetCount Sheets(sheetCounter).Activate Set foundRange = Cells.Find(What:=datatoFind, After:=Cells(1, 1), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Activate 'if datatoFind is found in search range If Not foundRange Is Nothing Then 'save the address of the first occurrence of datatoFind, in the strFirstAddress variable strFirstAddress = foundRange.Address Do 'Find next occurrence of datatoFind Set foundRange = foundRange.FindNext(foundRange) 'Place the address of this occurrence in the next cell down in the column that holds found values (i column) Cells(foundmatrixCounter, 9).Value = foundRange.Address 'Increment the loop counter for the i column foundmatrixCounter = foundmatrixCounter + 1 'The Loop ends on reaching the first occurrence of datatoFind Loop Until foundRange.Address = strFirstAddress End If Cells(1, 9).Value = foundmatrixCounter 'Put the total number of instances, in this case foundmatrixCounter, in Z1 Next sheetCounter If foundRange Is Nothing Then MsgBox ("Value not found") Sheets(currentSheet).Activate End If End Sub 

我收到错误

运行时错误424(需要对象)

在以下行上:

 Set foundRange = Cells.Find(What:=datatoFind, After:=Cells(1, 1), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Activate 

不知道这行或一般的代码在这里可能是错的。

删除行尾的.Activate。

没有必要激活任何东西。 但是,这种格式是不正确的。 它将类似于:

 Dim R as Range set R = Range("A1").Activate 

由于范围(“A1”)。激活不是一个对象(它是一个布尔),这将导致相同的错误

罗恩是对的。 设置你的范围对象,然后通过testing范围对象Nothing来检查是否finddatatoFind。 然后你可以激活范围。

Set foundRange = Cells.Find(What:=datatoFind, After:=Cells(1, 1), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) If Not foundRange Is Nothing Then foundRange.Activate