Please Note: This article is written for users of the following Microsoft Word versions: 97, 2000, 2002, and 2003. If you are using a later version (Word 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Word, click here: Copying and Pasting Field Codes.

Copying and Pasting Field Codes

by Allen Wyatt
(last updated October 26, 2015)

9

Fields codes can be quite helpful in a document. At some point, you may want to share a field code with someone. Perhaps you are preparing a training document that needs to show the codes as text, or you want to e-mail the field code to someone else.

Problem is, if you simply copy and paste the field code, it isn't the actual code that is pasted; it is the result of that field code. You can, of course, display the field code (Shift+F9), position the insertion point within the braces, carefully select all the characters except the closing brace, and then copy to the Clipboard.

This approach can get tedious in a big hurry, however. A better approach is to use a macro to display the field code and stuff the desired information into the Clipboard. The following macro does just that:

Sub StuffFieldCode()
    Dim sField As String
    Dim sTextCode As String
    Dim bSFC As Boolean
    Dim MyData As DataObject
    Dim sTemp As String
    Dim J As Integer

    Application.ScreenUpdating = False

    If Selection.Fields.Count = 1 Then
        bSFC = Selection.Fields.Item(1).ShowCodes
        Selection.Fields.Item(1).ShowCodes = True
        sField = Selection.Text
        sTextCode = ""
        For J = 1 To Len(sField)
            sTemp = Mid(sField, J, 1)
            Select Case sTemp
                Case Chr(19)
                    sTemp = "{"
                Case Chr(21)
                    sTemp = "}"
                Case vbCr
                    sTemp = ""
            End Select
            sTextCode = sTextCode & sTemp
        Next J

        Set MyData = New DataObject
        MyData.SetText sTextCode
        MyData.PutInClipboard
        
        Selection.Fields.Item(1).ShowCodes = bSFC
    End If

    Application.ScreenUpdating = True
End Sub

The macro begins by turning off the screen updating, then it checks to make sure that the selection includes only one field. (You should select the field you want before running the macro.) If it does contain a single field, then the field code for that field is displayed, assigned to a variable (sField), and then picked apart character by character. If the character being examined is the opening field brace—Chr(19)—then it is replaced with a regular opening brace. If it is a closing field brace—Chr(21)—then it is replaced with a regular closing brace. Finally, if the character is a end-of-paragraph marker (vbCr), then the character is ignored.

Finally, the PutInClipboard method is used to stuff the text version of the field code into the Clipboard. You can then use a regular paste command (Ctrl+V) to paste the field code in either a document, an e-mail, or another program.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (3844) applies to Microsoft Word 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Word (Word 2007 and later) here: Copying and Pasting Field Codes.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Changing the Attached Template

Templates, when attached to a document, can greatly affect how that document looks. You can change from one template to ...

Discover More

Creating a Normal Index

Adding an index to a document is an easy task. There are a couple of ways you can do it, as described in this tip.

Discover More

Complex Lookup Formulas

If you need to combine information in some of your cells in order to produce a result needed to, in turn, look up other ...

Discover More

Learning Made Easy! Quickly teach yourself how to format, publish, and share your content using Word 2013. With Step by Step, you set the pace, building and practicing the skills you need, just when you need them! Check out Microsoft Word 2013 Step by Step today!

MORE WORDTIPS (MENU)

Inserting the User's Initials

One of the pieces of information tracked by Word are your name and initials. You can insert your initials by using the ...

Discover More

Inserting Fields

Fields are used for a variety of dynamic purposes in a document. There are a couple of ways you can easily insert fields, as ...

Discover More

Using Mandatory Form Fields

When using form fields to gather information from users of your documents, you may want to make sure that some of the fields ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments for this tip:

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 9 - 7?

2016-06-21 04:26:36

Frances Cherman

Peter, this script worked perfectly – even on Word 2011 for Mac!


2016-05-04 12:36:05

Mats Linder

PS. Same thing with Dim MyData As DataObject.


2016-05-04 12:34:20

Mats Linder

Hi!

I get the following error: Compilation error. Own defined type is not defined.

This is for the line
Dim DataObj As New DataObject

I'm grateful for any help.

Mats


2014-06-03 09:47:38

matt

Awyatt,

Unfortunately that only works for single copy/paste efforts. I have multiple (>100) lines of text with field codes attached in the front (numbering) I would like to paste all the text into word and have it recognize the field code!


2014-02-18 09:45:24

awyatt

Scipio: The field code text (the stuff between the field braces) is what is copied to the Clipboard by the macro. If you want to use that in a different field elsewhere, then (1) position the insertion point where you want the new field, (2) press Ctrl+F9 to insert empty field braces, and (3) press Ctrl+V to paste the contents of the Clipboard into those empty field braces.

You can then update the newly created field by pressing F9.

-Allen


2014-02-18 08:21:14

Scipio

Wyatt’s Macro works...sort of.
The macro does indeed extract the text of the field code. Upon pasting the text into another document, however, only the text is preserved. Wyatt’s tutorial here is missing the key step: how does one convert the text back into a Microsoft Word field?
Any assistance in answering this question would be immensely appreciated.
Cordially,
Scipio


2014-01-21 12:11:52

Peter Straton

OK, a little embarrassed that I didn't test the empty-text condition. The following line,

DataObj.SetText ClipBoardText

should actually be:

If ClipBoardText = vbNullString Then
DataObj.SetText Text:=Empty 'Clear it
Else
DataObj.SetText Text:=ClipBoardText
End If


Apologies for any confusion.

Peter Straton


2014-01-16 13:38:35

Peter Straton

Hi Allen,

Thanks so much for this very useful bit of code! I've taken the liberty of futher generalizing it. Code included below...


Best regards,

Peter Straton


[code]
Sub CopyFieldCodeAsText()
'Copies all field codes from the selected document range to the clipboard, which can then be pasted to other
'documents or files as text.
'
'Author: Peter Straton
'
'Credit: Heavily leveraged from code by Allen Wyatt
' @ http://word.tips.net/T003844_Copying_and_Pasting_Field_Codes.html
'
'*************************************************************************************************************

Dim ClipBoardText As String
Dim CodeTxt As String
Dim DataObj As New DataObject 'Allocate it too
Dim EndPt As Long
Dim FieldTxt As String
Dim j As Integer
Dim SaveSelection As Range
Dim SaveShowCodes As Boolean
Dim Separator As String
Dim TempChr As String

Application.ScreenUpdating = False

Set SaveSelection = Selection.Range
EndPt = Selection.End

'IMPORTANT: Compound field codes are actually counted as multiple fields by Fields.Count, so the following
'Do While condition only test whether there are any top-level fields still to be processed. That is, you
'can't use a For loop on Fields.Count because it doesn't necessarily reflect the number of top-level fields.

Do While Selection.Fields.Count >= 1
'There is (still) at least one field in the currently selected range, so process it

Selection.Fields(1).Select 'Select just the (next) field
SaveShowCodes = Selection.Fields.Item(1).ShowCodes
Selection.Fields.Item(1).ShowCodes = True 'So that you can...
FieldTxt = Selection.Text '...get the field's code as text

'Parse the field text char-by-char and replace special chars with printable chars

CodeTxt = ""
For j = 1 To Len(FieldTxt)
TempChr = Mid(FieldTxt, j, 1)
Select Case TempChr
Case Chr(19) 'ASCII 19 (DC3) is start-field code, which displays as "{", but isn't.
TempChr = "{"
Case Chr(21) 'ASCII 21 (NAK) is end-field code, which displays as "}", but isn't.
TempChr = "}"
Case vbCr 'Compress the text by removing CR chars. [Is this actually of value?]
TempChr = ""
End Select
CodeTxt = CodeTxt & TempChr
Next j

ClipBoardText = ClipBoardText & Separator & CodeTxt
Selection.Fields.Item(1).ShowCodes = SaveShowCodes 'Restore for this field

Selection.Collapse wdCollapseEnd 'Move to next field, if any...
ActiveDocument.Range(Selection.Start, EndPt).Select

Separator = vbLf 'For multiple fields, separate their code listings on the clipboard with LF chars
Loop

'Write the results to the clipboard. If no fields were found, still overwrite the existing clipboard data
'with the empty string so that any subsquent Paste operation doesn't paste old data.

DataObj.SetText ClipBoardText
DataObj.PutInClipboard

SaveSelection.Select
Application.ScreenUpdating = True
End Sub
[/code]


2013-04-07 17:41:10

Barry Karas

what is a field code? Please give examples.


This Site

Got a version of Word that uses the menu interface (Word 97, Word 2000, Word 2002, or Word 2003)? This site is for you! If you use a later version of Word, visit our WordTips site focusing on the ribbon interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.

Links and Sharing