Software

Remove field codes from Word documents with this handy macro

Users sometimes need to clean up a Word document so they can send it to a production system or other publication platform without problematic elements like field codes. The Replace command can get the job done, but it's a bit tricky. This macro offers a simple, one-step solution for users of all experience levels.

This article is also available as a PDF download.

By Susan Sales Harkins and Bryan Carbonnelle

Word offers a number of useful features for managing large documents. For instance, you can mark specific words and phrases, which Word then uses to generate a table of contents, a table of authorities, a table of figures, and even an index. This can save you a lot of time. Instead of creating these pieces manually, you mark the text you want included in the table of contents, index, and so on, and Word inserts a field code. Once you've completed the document, Word generates your table of contents, index, and so on, according to those fields.

But a problem arises when you want to delete field codes. Word's Replace feature will delete them, but the process is a bit awkward. Alternatively, you can delete them manually. In a large manuscript with lots of fields, that could take hours. The good news is that you can use a macro to strip all those field codes in just a few seconds.

Who deletes field codes?

You might be wondering why you'd ever want to delete field codes. The truth is, most of the time, you won't. However, some processes require a clean copy of the content. By clean, we mean that a document contains no hidden formatting or codes. For instance, you might submit Word documents to a production system for publication in a magazine or journal. Or you might submit HTML documents for publication on a Web site.

To see how time-consuming it can be to strip a document of field codes, take a minute to insert a few fields into a document. Simply select a word and press [Alt][Shift]X. In the resulting Mark Index Entry dialog box, shown in Figure A, click the Mark button. Doing so inserts an index entry field code, as shown in Figure B. (Click Show/Hide on the Standard menu to toggle the code display.)

Figure A

We'll create some index entries using this dialog box to add fields to a document.

 

 

Figure B

When you click Mark, Word inserts an index entry code.

Now, imagine a 100-page document full of codes. You might approach the problem using the Replace command, but it's a little tricky and requires know-how that casual users might not have. First, you must display the codes. The problem is, will users remember to do that? If they don't, they might not even realize that Replace did not delete the codes.

After displaying the codes, you need to choose Replace from the Edit menu. Then, in the Find And Replace dialog, click More and then Special. Choose Field from the resulting list of special characters to enter ^d in the Find What text box. (The ^d component represents all field codes.) Leave the Replace With field empty, click Replace All, and Word deletes all of the field codes in the document.

A second problem with this route is that it deletes all of the field codes: index, table of contents, figures, and table of authorities—not to mention things like field-generated page numbers and dates. If you need to retain some of those fields, you'll have to jump through another hoop, combining the specific code for the field you want to eliminate with the ? wildcard. For instance, if you wanted to delete only the index fields, you'd enter ^d xe ^?. It's a lot of work even if you know what you're doing. An inexperienced user might have trouble.

The field-deleting macro

Fortunately, you can bypass the Replace technique and automate the field-stripping process with a simple macro. It does all the work. All you have to do is remember to run it. To add the macro to a document, do the following:

  1. With the Word document open, press [Alt][F11] to launch the Visual Basic Editor (VBE).
  2. In the VBE, choose Module from the Insert menu.
  3. Enter the following macro:

Sub DeleteIndexEntries()
  Dim doc As Document
  Dim fld As Field
  Set doc = ActiveDocument
  For Each fld In doc.Fields
    fld.Select
    If fld.Type = wdFieldIndexEntry Then
      fld.Delete
    End If
  Next
  Set fld = Nothing
  Set doc = Nothing
End Sub

Run the macro by pressing [F5] or by choosing Run Sub/UserForm from the Run menu. Or if you prefer, return to the document and choose Macro from the Tools menu. In the resulting Macros window, select DeleteIndexEntries and click Run.

The For...Each statement loops through the Fields collection and deletes each field type, as determined by the intrinsic constant. The example macro will delete all index field codes (wdFieldIndexEntry). To delete other field codes, simply substitute the intrinsic constant, accordingly. For instance, use wdFieldTOCEntry to delete table of contents entries or wdFieldTOAEntry to delete table of authority entries.


Tip

There are a number of field code types. To get a full list of constants for the wdFieldType class, use the Object Brower. In the VBE, press [F2] or choose Object Browser from the View menu. In the Classes list, find wdFieldType to update the Members list. Or simply highlight wdFieldIndexEntry in the subprocedure and press [Shift][F2] to display the constants in the Object Browser.


Worth noting

You can modify this macro to delete more than one field code type. If you require more flexibility, create a user form to pass the appropriate constant to the macro. That way, you can use the same macro to delete different field codes, as needed. Keep in mind that you must pass the constant's numeric value and not its name. For instance, the integer value for wdFieldIndexEntry is 4, so you would pass that value to the procedure.

You can store the macro with your manuscript document. If you do, be careful not to overwrite the original document containing the field codes. If you accidentally write over the original copy, you will lose all of the field codes. Later, when you update the original, you'll have to re-enter all those field codes if you need to regenerate the table of contents, index, and so on. Most likely, you want to save two files: The original with all the field codes and a clean copy with no field codes. We suggest that you store the macro in a code library and run it only against a second copy of your document.

 


Susan Sales Harkins is an independent consultant and the author of several articles and books on database technologies. Her most recent book is Mastering Microsoft SQL Server 2005 Express, with Mike Gunderloy, published by Sybex. Other collaborations with Gunderloy are Automating Microsoft Access 2003 with VBA, Upgrader's Guide to Microsoft Office System 2003, ICDL Exam Cram 2, and Absolute Beginner's Guide to Microsoft Access 2003, all published by Que. Currently, Susan volunteers as the Publications Director for Database Advisors. You can reach her at ssharkins@setel.com.

Bryan Carbonnell works for a public broadcaster in Canada. He has written several articles on automating Word for Access, which are available at Database Advisors. Bryan also volunteers as the site's listmaster. You can reach him at carbonnb@gmail.com.

11 comments
tim.mantyla
tim.mantyla

It fails and highlights the word "Dim" in this initial phrase: Sub DeleteIndexEntries() Dim doc There are 2 spaces ahead of "Dim" and 1 after it. Is something wrong w/ the code? I pasted it in verbatim, except for trading "wdFieldFootnoteRef" for "wdFieldIndexEntry" It fails whether or not I keep original entry for the "wd" area. Word 2007 Help, as is often the case, is obtuse and does not define a precise way to fix this problem. I don't know what "Dim" means. I don't know VBE, so maybe it's just not as obvious to me as it would be to a programmer? Please help!

Casey-Dronten
Casey-Dronten

This is great! But I needed an additional feature for it: Only remove index entries with specific heading levels. This is my solution: Note Because I use a Dutch Word 2003 version, the formate names are Dutch too. You should change Kop into heading; Voorwoord into Preface etc. Attribute VB_Name "IndexMarkeringenVerwijderen" ' IndexMarkeringenVerwijderen Macro ' Macro extended 25-1-2010 by Casey.Dronten ' 'There are a number of field code types. To get a full list of constants for the wdFieldType class, use the Object Brower. In the VBE, press [F2] or choose Object Browser from the View menu. In the Classes list, find wdFieldType to update the Members list. Or simply highlight wdFieldIndexEntry in the subprocedure and press [Shift][F2] to display the constants in the Object Browser. 'Tip Sub IndexMarkeringenVerwijderen() Dim doc As Document Dim fld As Field Set doc = ActiveDocument For Each fld In doc.Fields fld.Select If (Selection.ParagraphFormat.Style Like "Kop [0-9]") Or (Selection.ParagraphFormat.Style Like "Voorwoord") Or (Selection.ParagraphFormat.Style Like "Index") Then 'MsgBox Selection.ParagraphFormat.Style If fld.Type = wdFieldIndexEntry Then Response = MsgBox("Wilt u deze indexmarkering verwijderen? [" & Selection.Text & "] opmaakprofiel: " & Selection.ParagraphFormat.Style, vbYesNoCancel, "Indexmarkering verwijderen") If Response = vbYes Then fld.Delete End If If Response = vbCancel Then Exit For End If End If End If Next Set fld = Nothing Set doc = Nothing End Sub Casey

spykeee
spykeee

hi, i have a problem removing the 'return' character (the one that looks like a backwards 'L' with a little arrow on the bottom leg). It is not recognised by the find/replace function, and I can't copy it and then paste it into the 'find' field of find/replace. Any ideas or tips to do this? Ta.

IRGconserv
IRGconserv

Fantastic macro. I've been in a panic about how to remove 700 pages of field codes from a manuscript before sending it to a publisher. After creating the huge index, the only way I could find to remove the code was by deleting one by one. You have saved me many days of tedious work and headaches! Thanks.

popkov
popkov

Very useful macro! Thank you! But it doesn't work in footnotes... How it may be modifyed for this?

mhastings
mhastings

Would something like this work with Smart Tags as well? Also, is there a way to export Smart Tags to another document?

JodyGilbert
JodyGilbert

Do your users need to perform this type of document cleanup task on a regular basis? What other macros do you provide for automating specialized chores like this one?

popkov
popkov

I have written the macro that removes EndNote field codes (converts EndNote fields to text) in current Word document not only in endnotes and footnotes, but also in Shapes. This macro identifyes EndNote fields by it's type - ADDIN. That is the code: ------- code -------------------- Sub RemoveAddin_FieldCodes() nResult = VBA.Interaction.MsgBox("Вы уверены, хотите удалить все коды полей типа ADDIN?", vbOKCancel, "Действие необратимо!") If nResult = vbOK Then Dim doc As Document Dim fld As Field Dim ftnt As Footnote Dim endnt As Endnote Dim shp As Shape Dim shp2 As Shape Dim shp3 As Shape Set doc = ActiveDocument ActiveDocument.ActiveWindow.View.ShowFieldCodes = False For Each fld In doc.Fields ' fld.Result.Select If fld.Type = wdFieldAddin Then fld.Unlink End If Next fld For Each ftnt In doc.Footnotes For Each fld In ftnt.Range.Fields ' fld.Result.Select If fld.Type = wdFieldAddin Then fld.Unlink End If Next fld Next ftnt For Each endnt In doc.Endnotes For Each fld In endnt.Range.Fields ' fld.Result.Select If fld.Type = wdFieldAddin Then fld.Unlink End If Next fld Next endnt For Each shp In doc.Shapes If shp.Type = msoTextBox Then For Each fld In shp.TextFrame.TextRange.Fields ' fld.Result.Select If fld.Type = wdFieldAddin Then fld.Unlink End If Next fld End If If shp.Type = msoGroup Then For Each shp2 In shp.GroupItems If shp2.Type = msoTextBox Then For Each fld In shp2.TextFrame.TextRange.Fields ' fld.Result.Select If fld.Type = wdFieldAddin Then fld.Unlink End If Next fld End If Next shp2 End If If shp.Type = msoCanvas Then For Each shp2 In shp.CanvasItems If shp2.Type = msoTextBox Then For Each fld In shp2.TextFrame.TextRange.Fields ' fld.Result.Select If fld.Type = wdFieldAddin Then fld.Unlink End If Next fld End If If shp2.Type = msoGroup Then For Each shp3 In shp2.GroupItems If shp3.Type = msoTextBox Then For Each fld In shp3.TextFrame.TextRange.Fields ' fld.Result.Select If fld.Type = wdFieldAddin Then fld.Unlink End If Next fld End If Next shp3 End If Next shp2 End If Next shp Set fld = Nothing Set ftnt = Nothing Set doc = Nothing Set shp = Nothing Set shp2 = Nothing Set shp3 = Nothing End If End Sub -----------code----------------

IRGconserv
IRGconserv

I can't get the "footnote" macro to run--when I hit F5 it asks ????? about the second line of the macro: nResult = VBA.Interaction.MsgBox("Вы уверены, хотите удалить все коды полей т

Editor's Picks