CONTEXT
我正在尝试在特定列中搜索" 1月和#34;的所有实例。然后引用该行,以便我可以将单元格直接复制到它的左侧。单元格包含公式,所以我实际上是在搜索单元格的值而不是公式。
问题
我一直在尝试测试并确保它引用了正确的单元格地址(特别是行)。对于每个1月份的实例,它会粘贴"测试"在列的所有值的末尾而不是在FoundCell本身。 (例如,如果1月出现2次,它会不断循环"测试"在列的末尾)
Excel示例
Month Month
January =A2
February =A3
April =A4
April =A5
January =A6
December =A7
当前代码
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
Set myRange = Range("B:B")
Set LastCell = myRange.Cells(myRange.Cells.Count)
Set FoundCell = myRange.Find(what:=January, after:=LastCell, LookIn:=xlValues)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Do
MsgBox "Found it!"
FoundCell.Value = "Testing"
Set FoundCell = myRange.FindNext(FoundCell)
Loop While Not FoundCell Is Nothing And FoundCell.Address <> FirstFound
Else
MsgBox "Not Found!"
End If
Set rng = FoundCell
Exit Sub
如果您认为有什么可以提供帮助,请告诉我们!
答案 0 :(得分:1)
通过一些修改,我可以让你的代码运行。不确定您要做什么,但根据测试数据,此代码不再遇到代码在Loop While
遇到的运行时91错误:
Sub foo()
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
Set myRange = Range("B:B")
Set LastCell = myRange.Cells(myRange.Cells.Count)
Set FoundCell = myRange.Find(what:="January", after:=LastCell, LookIn:=xlValues)
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Do
' FoundCell.Interior.ColorIndex = 39
FoundCell.Offset(,1).Value = "Testing!" '<~~ I'm writing out to the adjacent cell, just to be safe. Modify as needed.
Set FoundCell = myRange.FindNext(FoundCell)
Loop While (FoundCell.Address <> FirstFound)
End If
Set rng = FoundCell '<~~ Careful, as this is only the LAST instance of FoundCell.
End Sub
答案 1 :(得分:-1)
你一遍又一遍地得到“测试”一词,因为你的循环正在搜索“测试”这个词,而不是“一月”。
-L
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Do
MsgBox "Found it!"
FoundCell.Value = "Testing"
Set FoundCell = myRange.FindNext(FoundCell)
Loop While Not FoundCell Is Nothing And FoundCell.Address <> FirstFound
Else
您要将单元格值设置为使用此行进行测试
FoundCell.Value = "Testing"
现在您正在搜索字符串“Testing”。 FoundCell是一个范围。我相信单元格区域的默认属性是单元格的值(即 - “测试”)
因此,您最初找到字符串“January”,将其更改为“Testing”,然后一遍又一遍地搜索字符串“Testing”,您将继续查找,因为您将继续将其写入每个循环的新单元格迭代。
至少看起来这就是我发生的事情,我实际上并没有尝试运行代码。您可以通过将Set FoundCell = myRange.FindNext(FoundCell)
更改为Set FoundCell = myRange.FindNext(FoundCell)