我已经完成了一些谷歌搜索,但无法找到为我的特定需求创建VBA宏代码的方法。我想要完成的是通过宏搜索我粘贴到Word中的一些XML代码,找到<CID>*</CID>
和<FirstName>*</FirstName>
之间的值,提取值,然后用新元素替换它格式:<FName id="*">*</FName>
,其中*表示通配符搜索两个元素标记之间的任何值。所以在我下面的XML代码示例中,我希望宏提取&#34; 59&#34;和&#34; John&#34;,删除整个代码并将提取的值过去为新的元素格式:<FName id"59">John</FirstName>
。我的代码和VMBA宏:
***XML Code***
<CustIDandName>
<CID>59</CID>
<FirstName>17</FirstName>
</CustIDandName>
将其更改为<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
答案 0 :(得分:1)
您可以使用Word通配符搜索并替换模式来实现此目的:
查找文字:
\<CID\>([0-9]*)\</CID\>*\<FirstName\>(*)\</FirstName\>
替换文字:
<FName id="\1">\2</FirstName>
由于替换文本包含引号,因此必须确保禁用自动替换带印刷引号的直引号。
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