Sub CallTextToFields()
Dim rng As Range
Set rng = Selection.Range
TextToFields rng
End Sub
Sub TextToFields(rng1 As Range)
Dim rng As Range
Dim fld As Field
Set rng = GetField(rng1)
Do Until rng Is Nothing
rng.Characters.First.Delete 'remove the "{"
rng.Characters.Last.Delete 'and the '}'
rng.Copy
Set fld = ActiveDocument.Fields.Add(rng, wdFieldEmpty, rng.Text, False)
fld.Code.Paste 'VBA bug. The line above corrupts nested fields, so we replace the range
Set rng = GetField(rng1)
Loop
End Sub
Function GetField(rng As Range) As Range
Dim rngStart As Long
Dim rng1 As Range
Dim bFound As Boolean
'looks for a potential field i.e. text bracketed with "{" and "}", but no contained "{"
Set rng1 = rng.Duplicate
bFound = True
Do While bFound
With rng1.Find
bFound = False
.Text = "{"
.MatchWildcards = False
If .Execute Then
bFound = True
rngStart = rng1.Start
rng1.Collapse wdCollapseEnd
rng1.End = rng.End
.MatchWildcards = True
.Text = "[\{\}]{1}"
If .Execute Then
If rng1.Characters.First.Text = "}" Then
rng1.Start = rngStart
Set GetField = rng1.Duplicate
Exit Function
End If
End If
rng1.Start = rngStart + 1
rng1.End = rng.End
End If
End With
Loop
End Function
As an adjunct, if you already have a worked-out field complex, and you want to show it outside of a Word document, this will do the rather simpler task of creating text from the fields.
Sub CallFieldsToText()
Dim rng As Range
Set rng = Selection.Range
FieldsToText rng
End Sub
Sub FieldsToText(rng As Range)
Dim fld As Field
Dim rnga As Range
Dim rnge As Range
For Each fld In rng.Fields
Set rnga = fld.Code
rnga.Copy
fld.Delete
rnga.Paste
Set rnge = rnga.Duplicate
rnga.Collapse wdCollapseStart
rnga.Text = "{"
rnge.Collapse wdCollapseEnd
rnge.Text = "}"
Next fld
End Sub
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (3)
Commented:
This sounds like a very useful and interesting concept. Unfortunately, neither of the above work with Word 2010. The first macro errors out on the line
Debug.Print rng.Text
with the message "Object variable or With block variable not set".
The second macro errors out with "Wrong number of arguments or invalid property assignment" and highlights
FieldsToText
in the line
FieldsToText rng
of the sub
Sub CallFieldsToText()
I've placed the code in a standard module in my Normal template. I open the document with the field codes, hit Alt-F9 to show field codes and select the field code block, then run either Sub CallTextToFields() or Sub CallFieldsToText()
What am I doing wrong?
Author
Commented:You did nothing wrong, and it's not the Word version.
I seem to have pasted test versions in at some time. I have now replaced them with newer versions.
Commented:
Thank you !!!