Sub FieldStringToCode()
' Based on a macro provided by Paul Edstein
' Converts "textual" field codes into real field codes
' To do the conversion, simply paste the "textual" field codes
' into your document, select them and run the macro.
Dim RngFld As
Range
Dim RngTmp As
Range
Dim oFld As
Field
Dim StrTmp As String
Dim sUpdate As String
Dim bFldCodes As Boolean
Const Msg1 = "Select the text to convert
and try again."
Const Msg2 = "There are no field strings in
the selected range."
Const Msg3 = "Unmatched field brace pairs
in the selected range."
Const Title1 = "Error!"
Const Title2 = "Update fields?"
Application.ScreenUpdating = False
bFldCodes = ActiveDocument.ActiveWindow.View.ShowFieldCodes
If Selection.Type <> wdSelectionNormal
Then
MsgBox Msg1, vbExclamation
+ vbOKOnly, Title1
Exit
Sub
End If
If InStr(1, Selection.Text, "{") = 0 Or
_
InStr(1, Selection.Text,
"}") = 0 Then
MsgBox Msg2, vbCritical +
vbOKOnly, Title1
End If
If Len(Replace(Selection.Text, "{", vbNullString)) <> _
Len(Replace(Selection.Text,
"}", vbNullString)) Then
MsgBox Msg3, vbCritical +
vbOKOnly, Title1
Exit
Sub
End If
ActiveDocument.ActiveWindow.View.ShowFieldCodes =
True
Set RngFld = Selection.Range
With RngFld
.End = .End + 1
Do
While InStr(1, .Text, "{") > 0
Set RngTmp = ActiveDocument.Range(Start:=.Start + _
InStr(.Text, "{") - 1, _
End:=.Start + InStr(.Text, "}"))
With RngTmp
Do While Len(Replace(.Text, "{", vbNullString)) <> _
Len(Replace(.Text, "}", vbNullString))
.End = .End + 1
If .Characters.Last.Text <> "}"
Then .MoveEndUntil cset:="}", _
Count:=Len(ActiveDocument.Range(.End, RngFld.End))
Loop
.Characters.First = vbNullString
.Characters.Last = vbNullString
StrTmp = .Text
Set oFld = ActiveDocument.Fields.Add(Range:=RngTmp, _
Type:=wdFieldEmpty, _
Text:="", _
PreserveFormatting:=False)
oFld.Code.Text = StrTmp
End With
Loop
ActiveDocument.ActiveWindow.View.ShowFieldCodes = bFldCodes
.End = .End - 1
If bFldCodes = False
Then .Fields.ToggleShowCodes
.Select
End With
Application.ScreenUpdating = True
sUpdate = MsgBox("Do you wish to update the fields?" & vbCr + vbCr & _
"Note that if the converted fields include ASK or FILLIN fields, " & _
"updating will force the prompt for input to those fields", vbYesNo,
Title2)
If sUpdate = vbYes
Then RngFld.Fields.Update
Set RngTmp = Nothing
Set RngFld = Nothing
Set oFld = Nothing
End Sub