PDA

View Full Version : Find and number tags



marsy00
09-07-2012, 01:45 PM
I have a requirements document with a number of "tags" in it of the form "GW:xxx"

I'd like to write a macro to number all of these tags in order. So far, I've done this:

With Selection
.HomeKey wdStory
With .Find
Do While .Execute(findText:="GW:", _
MatchWildcards:=True, _
Wrap:=wdFindStop, Forward:=True) = True
Set rngReqTag = Selection.Range

rngReqTag.MoveEnd (wdWord)

strReqTag = "GW:" & i
rngReqTag.Text = strReqTag
i = i + 1
Loop
End With
End With


The problem with this is that it continuously loops on the first found tag, it never advances to the subsequent tags further down in the document. Can anyone offer any advice?

Also, can someone point me to a good tutorial/overview of vba for word? I've written some macros in excel and I'm familiar with coding in general, but I'm having a hard time getting past the learning curve with the various key words, methods, etc. Googling didnt seem to yield anything too helpful for a high level overview.

Thanks!

fumei
09-07-2012, 02:36 PM
Try:Sub yadda()
Dim r As Range
Dim i As Long
i = 1
Set r = ActiveDocument.Range
With r.Find
Do While .Execute(findText:="GW:", _
MatchWildcards:=True, _
Wrap:=wdFindStop, Forward:=True) = True
r.InsertAfter i
r.Collapse 0
i = i + 1
Loop
End With
End SubIt is better is use Range, rather than Selection. Your problem is that you need to move the focus to PAST the found string (GW: plus i). this is done with Collapse in the code above. The code:

1. finds GW:, which makes the range object THAT- GW:
2. inserts the Long i after which makes the range object THAT - GW: i
3. Collapses the range object to the end - which makes the range object a point AFTER GW: i.

Continue on.