运行宏时收到此错误消息:
运行时错误' 6':溢出
我有两张工作表;搜索和数据。 '数据'工作表包含两列,A列包含我想要搜索的数字,B列包含字母数字值我要复制并粘贴到'搜索'找到数字匹配时的工作表。因为我正在搜索的数字可以列出未知次数我想要一个宏循环查找所有实例,将值复制到其右边并将其粘贴到'搜索'单元格D3中的工作表,并向下找到要找到的数字的多个实例的行。
我正在搜索的号码可以在'搜索'的单元格B3中找到。工作表。
这是'数据'工作表看起来像:
ID ISS_ID
108143 136KQV4
108143 173HBK3
108143 136KQX0
109728 7805JM1
109706 7805JM1
102791 23252T4
105312 6477LZ6
以下是我现在的代码:
Sub Acct_Search()
Dim searchResult As Range
Dim x As Integer
x = 3
' Search for "Activity" and store in Range
Set searchResult = Worksheets("Data").Range("A1:A3500").Find(What:=Worksheets("Search").Range("B3"), _
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, _
SearchFormat:=False)
' Store the address of the first occurrence of this word
firstAddress = searchResult.Address
Do
' Set the value in the O column, using the row number and column number
Worksheets("Search").Cells(x, 4) = searchResult.Offset(0, 1).Value
' Increase the counter to go to the next row
x = x + 1
' Find the next occurrence of "Activity"
Set searchResult = Cells.FindNext(searchResult)
' Check if a value was found and that it is not the first value found
Loop While Not searchResult Is Nothing And firstAddress <> searchResult.Address
End Sub
当我调试时,它指向x = x + 1
行。现在它能够复制并粘贴第一个值而不会出现问题,但是在此之后错误就会发挥作用。
答案 0 :(得分:0)
更改
Dim x As Integer
到
Dim x As Long
答案 1 :(得分:0)
您的问题已更改,因为您未使用Range.FindNext Method的After:=...
参数重置搜索的原点。是的,您正在传递 searchResult ,但它不接受它作为After:=参数。
当我运行你的代码时,由于FindNext始终找到相同的第二个实例,我被抛入无限循环。这解释了当增加超过2 15时的整数咳嗽。当它被改变为很长时间时,这给了别的时间来扼杀。
在我更改了一行以明确包含命名参数后,一切都被清除了。
Set searchResult = Cells.FindNext(After:=searchResult)
只需添加/删除参数名称即可重现。似乎Cells.FindNext(searchResult)
找到了搜索!B3,因为那不是 firstAddress ,它只是在同一个搜索上继续循环!B3。直到我强迫after:=searchResult
.FindNext
调整了自己。在这些时候我更喜欢我的C / C ++日,没有这种沉重的开销。
我已经查看了您的代码,并添加了一个With ... End With
块,可以阻止任何可疑的父母。
Sub Acct_Search()
Dim searchResult As Range, firstAddress As String
Dim x As Long, ws As Worksheet
x = 3
Set ws = Worksheets("Search")
' Search for "Activity" and store in Range
With Worksheets("Data").Range("A1:A3500")
Set searchResult = .Find(What:=ws.Range("B3"), LookIn:=xlFormulas, After:=.Cells(.Rows.Count, .Columns.Count), _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
' Store the address of the first occurrence of this word
firstAddress = searchResult.Address
Do
' Set the value in the O column, using the row number and column number
ws.Cells(x, 4) = searchResult.Offset(0, 1).Value
' Increase the counter to go to the next row
x = x + 1
' Find the next occurrence of "Activity"
Set searchResult = .FindNext(After:=searchResult)
'Debug.Print searchResult.Address(0, 0, external:=True)
' Check if a value was found and that it is not the first value found
Loop While Not searchResult Is Nothing And firstAddress <> searchResult.Address
End With
Set ws = Nothing
End Sub
虽然不再需要After:=
参数,但我已将其保留。{/ p>