简体   繁体   中英

Is it possible to use a Word macro to replace one mail merge field with another?

I have Word Mail Merge document with merge codes inserted. I was wondering if I can write a Word macro to search for one mail merge code and replace it with another? I have tried, but the merge code I replace reverts back to the original value. I create a Word macro and use CTRL + H, put the data in to search and replace for(The merge fields) and click replace. It replaces the data, but after I save and return to document the old merge code is still there. The following vba code is generated:

  Selection.Find.ClearFormatting 
  Selection.Find.Replacement.ClearFormatting 
  With Selection.Find 
    .Text = "F_400" 
    .Replacement.Text = "F_901" 
    .Forward = True
    .Wrap = wdFindContinue 
    .Format = False 
    .MatchCase = False 
    .MatchWholeWord = False 
    .MatchWildcards = False 
    .MatchSoundsLike = False 
    .MatchAllWordForms = False 
 End With 
 Selection.Find.Execute

I am replacing merge field F_400 with merge field F_901.

In order to replace the name of a Mergefield you need to work with the underlying field code. What you normally see is a "pretty view" presented by Word, that can be switched between "field name" and the data preview provided by the Mailings tab in the Ribbon.

In order to use Find/Replace directly on the field codes, use Alt+F9 to toggle to the field code view. You should then see { MERGEFIELD fieldname }. In this state, you can Find fieldname and Replace it with a different, valid field name from the data source.

In order to toggle the field codes display as part of a macro so that you can use Find/Replace in VBA, use a Window object with the View.ShowFieldCodes property, for example:

ActiveWindow.View.ShowFieldCodes = True 'False to turn them off

This works fine when using Selection.Find. For Range.Find there's an alternate approach, by changing the TextRetrievalMode for the Range object being used for the Find:

rngFind.TextRetrievalMode.IncludeFieldCodes
With rngFind
   'and so on

The IncludeFieldCodes property picks up the "hidden" field codes for the code processing, so it doesn't matter whether the field codes are displayed on-screen, or not.

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