我想重命名Word文档中的合并字段。我使用以下脚本(基于使用VBA更改Word MailMerge字段的值)。我运行脚本,看到字段名被新值替换。但如果我用Alt+F9切换,我看到的是旧名字,当我再次切换时,我看到的是新名字。当我执行邮件合并时,它没有合并。
我需要做什么来改变两个名字?
Sub RenameMergeFields()
Dim f As Word.Field
form_old = InputBox("Vul de oude formuliernaam in.", "Formname old", "FVDL_Medewerker_Oproepkracht")
form_new = InputBox("Vul de nieuwe formuliernaam in.", "Formname new", "FVDL_Medewerker_Oproep_Omzetting")
ActiveDocument.TrackRevisions = False
If form_old <> "" And form_new <> "" Then
For Each f In ActiveDocument.Fields
'If f.Type = wdFieldIf Then
'End if
Debug.Print "Code: " & f.Code & Chr(13)
Debug.Print "Index: " & f.Index & Chr(13)
If f.Type = wdFieldMergeField Then
strReplace = Replace(f.Code, form_old, form_new)
strReplace = "{" & strReplace & "}"
f.Result.Text = strReplace
End If
Next
End If
End Sub
您不需要遍历字段。您可以使用查找/替换。例如:
Sub RenameMergeFields()
Application.ScreenUpdating = False
Dim form_old As String, form_new As String, bTrk As Boolean, bSFC As Boolean
With ActiveDocument
bTrk = .TrackRevisions
.TrackRevisions = False
bSFC = ActiveWindow.View.ShowFieldCodes
ActiveWindow.View.ShowFieldCodes = True
form_old = InputBox("Vul de oude formuliernaam in.", "Formname old", "FVDL_Medewerker_Oproepkracht")
form_new = InputBox("Vul de nieuwe formuliernaam in.", "Formname new", "FVDL_Medewerker_Oproep_Omzetting")
If form_old = "" Or form_new = "" Then Exit Sub
With .Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "MERGEFIELD " & form_old
.Replacement.Text = "MERGEFIELD " & form_new
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
ActiveWindow.View.ShowFieldCodes = bSFC
.TrackRevisions = bTrk
End With
Application.ScreenUpdating = True
End Sub