我正在尝试使用宏来搜索Excel工作簿中的某个字符串。我想获取找到该字符串的单元格的地址,并将它们一个接一个地放在当前工作表的I
列中。我的代码和问题如下。
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
不确定该行或一般代码在这里可能是错误的。
答案 0 :(得分:2)
删除该行末尾的.Activate。
没有必要激活任何东西。 但是,这种格式也是不正确的。它类似于:
Dim R as Range
set R = Range("A1").Activate
由于范围(" A1")。激活不是对象(它是布尔值),会导致相同的错误
答案 1 :(得分:0)
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