PDA

View Full Version : Loop for Word macro



Pwyll2
04-06-2015, 06:56 PM
Hello

I don't know much about VBA and I made a macro in Word with the Recorder Function. But I need to make a loop and I've no idea how to do that, and I don't understand what is explained on websites about VBA... It's always like Greek to me.

Basically, my macro is meant to do this:

<a name="">blablablah</a>

should become

<a name="blablablah">blablablah</a>

ie. what is between the tags should be copied and pasted between the " " in the tag just before. And this in every case with <a name="">TEXT</a>
until the end of the document.


Here is my macro:


Sub Ernault2_ancre_entree()
'
' Ernault2_ancre_entree Macro
' Macro enregistrée le 07/04/2015 par Pwyll2
'
Selection.Find.ClearFormatting
With Selection.Find
.Text = "\<a name=\""\""\>"
.Replacement.Text = "</b>"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With

Selection.Find.Execute
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.Find.ClearFormatting

With Selection.Find
.Text = "*\<\/a\>"
.Replacement.Text = "</b>"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute


Selection.MoveLeft Unit:=wdCharacter, Count:=4, Extend:=wdExtend
Selection.Copy
Selection.MoveLeft Unit:=wdCharacter, Count:=3
Selection.PasteAndFormat (wdPasteDefault)



End Sub

Where should I write Loop and other things so that the macro does the task until the end of the document?

Thanks a lot in advance!

gmayor
04-06-2015, 10:18 PM
You don't need a macro to do this. If your quoted texts are an accurate reflection of the problem, then use a wildcard search for

(\<a [a-z]{2,}=")("\>)([a-z]{1,})(\<\/a\>)

replace with

\1\3\2\3\4

http://www.gmayor.com/replace_using_wildcards.htm

Pwyll2
04-07-2015, 03:36 AM
Thanks for answering. But for some reason, it doesn't work. Word says "the searched text contains a special criterion that isn't valid" (well I'm trying to translate since my Word is in French).
But I tried to replace (\<a name=")("\>)(*)(\<\/a\>) by \1\3\2\3\4 and it works.

So thanks a lot, I didn't know it was possible to do that simply with the Search/Replace function of Word!
Thanks you

gmayor
04-07-2015, 04:02 AM
If you are working in a French version of Word, replace the commas with semi colons i.e.

(\<a [a-z]{2;}=")("\>)([a-z]{1;})(\<\/a\>)

The list character in your regional version will be ; not ,

Note this is preferable to using the blunt instrument that is *