简体   繁体   中英

VBA find-replace macro for MSWord 2013

I've done some googling and was not able to find a way to create a VBA macro code for my specific need. What I'm trying to accomplish is having the macro search through some XML code I paste into Word, find the value between <CID>*</CID> and <FirstName>*</FirstName> , extract the values, then replace it with the new element format: <FName id="*">*</FName> , where * represents a wild card search for any value between the two element tags. So in my XML code example below, I want the macro to extract "59" and "John", delete the whole code and past the extracted values to new element format: <FName id"59">John</FirstName> . My code and VMBA macro:

***XML Code***
<CustIDandName>
    <CID>59</CID>
    <FirstName>17</FirstName>
</CustIDandName>

Changing it to <FName id="59">John</FName>

***Word VBA Macro Code I have so far...***
    With Selection.Find
        .Text = "\<FirstName\>*\<\/FirstName\>"
        .Replacement.Text = "<FName id="59">John</FName>"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

You can achieve this using a Word wildcard search and replace pattern:

Find text:

\<CID\>([0-9]*)\</CID\>*\<FirstName\>(*)\</FirstName\>

Replacement text:

<FName id="\1">\2</FirstName>

As the replacement text contains quotes, you must make sure that the automatic replacement of straight quotes with typographic quotes is disabled.

Dim AutoFormatAsYouTypeReplaceQuotes As Boolean
Dim AutoFormatReplaceQuotes As Boolean

' remember auto correct options
AutoFormatAsYouTypeReplaceQuotes = Options.AutoFormatAsYouTypeReplaceQuotes
AutoFormatReplaceQuotes = Options.AutoFormatReplaceQuotes

' disable auto correct of quotes
Options.AutoFormatAsYouTypeReplaceQuotes = False
Options.AutoFormatReplaceQuotes = False

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "\<CID\>([0-9]*)\</CID\>*\<FirstName\>(*)\</FirstName\>"
    .Replacement.Text = "<FName id=""\1"">\2</FirstName>"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM