我试图使用宏来搜索特定字符串的Excel工作簿。我想获取找到字符串的单元格的地址,并将它们一个接一个地放在当前工作表的第I
列中。我的代码和问题如下。搜索工作簿的字符串 - 运行时错误424(对象需要)
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'因为当它没有找到任何东西,它不能激活细胞,这实际上是导致错误 – tigeravatar 2014-12-02 19:57:44
@tigeravatar,会出现错误它是否发现一些东西。 – 2014-12-02 20:03:25
@RonRosenfeld真的吗?这很奇怪。当我没有'.Activate'测试它时,它对我成功运行。当然,当我使用'.Activate'运行它时,我得到一个“Object variable not set”错误,而不是错误OP正在变得难以捉摸 – tigeravatar 2014-12-02 20:19:34