问题
What I want to do:
- Go through a document and look for word1
- Replace word1 with word2
- Change the word2 (increment it)
- Do 1-3 until word1 is replaced everywhere
My code so far:
With ThisDocument.Range.Find ' search the Document
.Text = "RS.0569/14.xxxxx" ' for this text
.Replacement.Text = nextID ' replace it with an ID ( Start= 0 )
Do ' loop the .execute part to increment my ID and only touch one ID at a time
.Execute Replace:=wdReplaceOne ' only replace one word per loop
nextID = Val(Split(nextID, ".")(2)) + 1 ' this is just ID+1
nextID = "RS.0569/14.0000" + nextID ' put the ID together
If Not .Found Then Exit Do ' Loop should stop if everything is replaced
Loop
End With
Problem: The Loop only runs 1 time because the Boolean .Found doesn't work with the loop -> I did "Debug.print .Found" before and after the .execute and the output was -> "False, True, True, False"
It looks like the .execute just switches the boolean which was False before but when the loop repeats the .execute it just switches it to "false" ( because it was true before)
Any idea? I have no idea for a workaround so I'm asking here...
回答1:
I have done a little bit with word before, the .Find
object is kind of tricky to work with especially because I do not do much Word automation, but I believe this should be working:
Dim fnd as Find
nextId = "RS.0569/14.00000"
Set fnd = ThisDocument.Range.Find
fnd.Text = "RS.0569/14.xxxxx"
Do
nextId = Val(Split(nextId, ".")(2)) + 1
nextId = "RS.0569/14.0000" & CStr(nextId) ' put the ID together
fnd.Replacement.Text = nextId ' replace it with an ID ( Start= 0 )
fnd.Wrap = wdFindContinue
fnd.Execute Replace:=wdReplaceOne ' only replace one word per loop
Loop Until fnd.Found = False
It was trial & error, mostly; I think the .Wrap
is what you need to allow it to continue.
来源:https://stackoverflow.com/questions/23497064/find-replace-with-loop-doesnt-work-the-way-i-want