Macro code to convert text to fields in Microsoft Word

AID: 7236
  • Status: Published

5820 points

  • ByGrahamSkan
  • TypeTips/Tricks
  • Posted on2011-08-22 at 06:15:25
Awards
  • Experts Exchange Approved
It is often necessary in this forum and others to illustrate Word fields as text with the field delimiters replaced with the curly brackets that the delimiters resemble when field codes are being displayed on the document. This means that the text cannot be used by simply be copying and pasting into another Word document. Each field must be inserted individually.

Sometimes there can be a complex structure of nested fields, in which case the task can be quite tricky. Here is a relatively simple example from a recent question.

{ IF {Mergefield creditors) > 300 "Employee 1
Employee 2
Employee 3" "{IF {Mergefield creditors} > 200 "Employee 1
Employee 2" "Employee 1" }" }


This macro set converts such text into the fields that it tries to portray. There is no error checking, so the text would have to be well-formed.  
 
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
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:

Select allOpen in new window


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
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:

Select allOpen in new window



To enter the macros into your Word template, switch to the VBA editor using Alt+F11.  The default top-left pane is the Project Explorer window. If you can’t see it, try using Ctrl+R to open it.

One of the projects will be the Normal project which holds the code for the Normal template. Use this project unless you have a reason to use another. All macros in the Normal template will be available to all documents. The code must go into a module, so if there are none in the project, add one via the Insert menu.

The code editor pane is the large one at the top-right. Paste or type your code in here.

While you have the VBA IDE open, you can easily run any macro that does not have any input parameters (aka arguments); macros which do have parameters have to be called from another macro. Simply place the text cursor somewhere in the macro code and press F5.

The two procedures to start here are the CallTextToFields and CallFieldsToText Subs. Set the document to show fields codes (Alt+F9). Select the text that you wish to convert and run the relevant procedure.
Asked On
2011-08-22 at 06:15:25ID7236
Tags

Word Fields VBA

Topic

Microsoft Word

Views
504

Comments

Expert Comment

by: teylyn on 2012-01-18 at 22:39:13ID: 34609

Hello,

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 Comment

by: GrahamSkan on 2012-01-19 at 02:30:35ID: 34629

Thank you teylyn.

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.

Expert Comment

by: teylyn on 2012-01-19 at 23:32:51ID: 34646

Wow! Very neat.

Thank you !!!

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top MS Word Experts

  1. GrahamSkan

    296,430

    Guru

    2,000 points yesterday

    Profile
    Rank: Genius
  2. teylyn

    43,476

    2,400 points yesterday

    Profile
    Rank: Genius
  3. chris_bottomley

    42,500

    0 points yesterday

    Profile
    Rank: Genius
  4. EricFletcher

    32,732

    0 points yesterday

    Profile
    Rank: Sage
  5. dlmille

    31,800

    0 points yesterday

    Profile
    Rank: Genius
  6. thinkpads_user

    21,832

    0 points yesterday

    Profile
    Rank: Genius
  7. finalword

    18,868

    0 points yesterday

    Profile
    Rank: Guru
  8. l33tf0b

    17,269

    0 points yesterday

    Profile
    Rank: Wizard
  9. BillDL

    15,550

    0 points yesterday

    Profile
    Rank: Genius
  10. Flyster

    15,000

    0 points yesterday

    Profile
    Rank: Sage
  11. puppydogbuddy

    14,700

    0 points yesterday

    Profile
    Rank: Genius
  12. paulsauve

    13,968

    2,000 points yesterday

    Profile
    Rank: Sage
  13. matthewspatrick

    13,186

    10 points yesterday

    Profile
    Rank: Savant
  14. PandaPants

    13,000

    0 points yesterday

    Profile
    Rank: Master
  15. regmigrant

    12,500

    0 points yesterday

    Profile
    Rank: Guru
  16. KCTS

    11,953

    0 points yesterday

    Profile
    Rank: Genius
  17. Helen_Feddema

    11,826

    0 points yesterday

    Profile
    Rank: Genius
  18. aikimark

    11,500

    0 points yesterday

    Profile
    Rank: Genius
  19. CodeCruiser

    9,000

    0 points yesterday

    Profile
    Rank: Genius
  20. GasperK

    8,498

    0 points yesterday

    Profile
    Rank: Master
  21. RobSampson

    8,200

    0 points yesterday

    Profile
    Rank: Genius
  22. motnahp00

    8,136

    0 points yesterday

    Profile
    Rank: Sage
  23. TBone2K

    7,600

    0 points yesterday

    Profile
    Rank: Sage
  24. ogctech

    7,600

    0 points yesterday

    Profile
  25. Rartemass

    7,400

    0 points yesterday

    Profile
    Rank: Wizard

Hall Of Fame