我在vba很新。我在excel中搜索字符串也可以多次出现,然后在每次出现时更改另一个文本(如果找到此字符串)。但我的代码进入无限循环。我怎样才能实现这一目标?这是我的代码:
Private Sub PRODA_Replace_IfNDM_Click()
Dim FindWord As String, Found As Range
Dim firstAddress As String
Dim rslt As Range
FindWord = "/*_NDM*"
Set Found = Sheets("PRODA").Cells.Find(What:=FindWord, _
LookIn:=xlValues, _
lookAt:=xlPart, _
searchOrder:=xlByRows, _
searchDirection:=xlNext, _
MatchCase:=False)
If Not Found Is Nothing Then
firstAddress = Found.Address
Do
Set rslt = Sheets("PRODA").Cells.Find(What:="OWNER:*", _
After:=Found, _
LookIn:=xlValues, _
lookAt:=xlPart, _
searchOrder:=xlByRows, _
searchDirection:=xlNext, _
MatchCase:=False)
Sheets("PRODA").Cells.Replace What:=rslt, _
Replacement:="OWNER:chrndm", _
lookAt:=xlPart, _
searchOrder:=xlByRows, _
MatchCase:=False, _
searchFormat:=False, _
ReplaceFormat:=False
MsgBox Found
If Found Is Nothing Then
GoTo endFinding
End If
Set Found = Cells.FindNext(After:=Found)
Loop While Not Found Is Nothing And firstAddress <> Found.Address
End If
endFinding:
MsgBox "changed successfully"
End Sub
答案 0 :(得分:1)
假设,对于findword
字符串的每次出现,下一次出现的"OWNER:*"
是要更改的字符串,以下代码将有希望起作用:
Private Sub PRODA_Replace_IfNDM_Click()
Dim FindWord As String, Found As Range
Dim ownerCell As Range
Dim firstAddress As String
Dim rslt As Range
FindWord = "/*_NDM*"
With Sheets("PRODA")
Set Found = .Cells.Find(What:=FindWord, _
LookIn:=xlValues, _
lookAt:=xlPart, _
searchOrder:=xlByRows, _
searchDirection:=xlNext, _
MatchCase:=False)
If Not Found Is Nothing Then
firstAddress = Found.Address
Do
Set ownerCell = .Cells.Find(What:="OWNER:*", _
After:=Found, _
LookIn:=xlValues, _
lookAt:=xlPart, _
searchOrder:=xlByRows, _
searchDirection:=xlNext, _
MatchCase:=False)
If ownerCell Is Nothing Then
MsgBox "No corresponding owner for word found at " & Found.Address
Exit Sub
End If
ownerCell.Value = "OWNER:chrndm"
'Can't do FindNext, because we did a different Find
Set Found = .Cells.Find(What:=FindWord, _
After:=Found, _
LookIn:=xlValues, _
lookAt:=xlPart, _
searchOrder:=xlByRows, _
searchDirection:=xlNext, _
MatchCase:=False)
If Found.Address = firstAddress Then
Exit Do
End If
Loop
MsgBox "changed successfully"
End If
End With
End Sub
我已经测试了一些虚拟数据,希望能够复制你正在做的事情。