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: Importing a Text File and Inserting after a Bookmark.

Importing a Text File and Inserting after a Bookmark

Written by Allen Wyatt (last updated December 1, 2018)
This tip applies to Word 97, 2000, 2002, and 2003


1

James has a program, external to Word, that automatically creates a small text file on a regular basis. (The text file always has the same name.) James thinks it would be nice to have a macro that could import the text file into a Word document and insert it right after a bookmark he has defined in the document.

There are a couple of ways you can approach this problem. If the goal is to simply include whatever the current contents of the text file are, then you wouldn't need a macro—just use the INCLUDETEXT field to reference the file you want included. Each time you update the fields in your document, Word goes out and grabs the current contents of the text file and includes it in your document.

If, however, you want to continually add the current contents of the text file to your document, then you will need to use a macro. One simple approach is to use the INCLUDETEXT field within the macro itself, in this manner:

Sub InsertTextFileAfterBookmark1()
    With Selection
        .GoTo what:=wdGoToBookmark, Name:="mybmk"
        .Fields.Add Range:=Selection.Range, _
          Type:=wdFieldIncludeText, Text:="c:\\myfile.txt \c" _
          & Chr(32) & "plaintext" & Chr(32) & ""
        .MoveLeft , 1
        .Fields.Unlink
        .MoveEnd
    End With
End Sub

The macro jumps to the location of the bookmark, inserts an INCLUDETEXT field, selects the field, and then unlinks it. The result is that the contents of the text file are inserted in the document. The purpose of unlinking the field is to, essentially, get rid of the INCLUDETEXT field, replacing it with the results of that field (the file contents).

To use the macro, simply change the code to reflect the name of the bookmark and the full path to the text file you want to insert. Also, make sure you use double backslashes within the path specification; this is required for the field code to work properly.

Another approach is to forego the INCLUDETEXT field altogether and simply insert the contents of the file. The following version of the macro does just that:

Sub InsertTextFileAfterBookmark2()
    If ActiveDocument.Bookmarks.Exists("mybmk") = True Then
        ActiveDocument.Bookmarks("mybmk").Select
        Selection.InsertFile FileName:="c:\myfile.txt"
    Else
        MsgBox "Bookmark ""mybmk"" does not exist!"
    End If
End Sub

The macro checks for the existence of the bookmark named mybmk (you can and should change this) and then uses the InsertFile method to insert the contents of the file. You should realize that, as written, the macro will overwrite the bookmark. If you want to make sure that the bookmark remains intact, then you'll need to add a line of code to collapse the bookmark to its endpoint, just before inserting the file:

        Selection.Collapse Direction:=wdCollapseEnd

Your macro can be as fancy as you want it, of course. The following example shows a more full-featured macro that gives you the option of specifying how much space to put between the bookmark and the file contents you want to insert. All you need to do is make sure you adjust the macro at points (1), (2), and (3) to reflect how you want it to operate. (The comments in the macro explain what the expectations and options are.)

Sub InsertTextFileAfterBookmark3()
    ' This macro reads the contents of a specified text file
    ' and inserts the text after a particular bookmark in
    ' the active document.

    Dim InsertSpacer As Integer
    Dim FileContent As String

    ' (1) Pick a number to insert something between the
    '     bookmark and the inserted text as spacing:
    '     0 = No space. Text is inserted immediately
    '         after the bookmark
    '     1 = Insert one space between bookmark and text
    '     2 = Insert paragraph mark between bookmark and text
    '     3 = Insert 2 paragraph marks between bookmark
    '         and text

    InsertSpacer = 1

    ' (2) Set a constant for the name of the file to import.
    '     Change the file name inside the quotes below to
    '     the full path and file name of the text file to
    '     import:

    Const TextFile As String = "c:\myfile.txt"
   
    ' (3) Change the file name in the quotes below to the
    '     name of the bookmark after which you want to
    '     insert the text:

    Const BookmarkName As String = "mybmk"

    ' Handle errors
    On Error GoTo Oops

    ' Open and grab contents of the file
    Open TextFile For Input As #1
    FileContent = Input(LOF(1), #1)
    Close #1

    ' Find the bookmark in the active document
    Selection.GoTo What:=wdGoToBookmark, Name:="MyBookmark"

    ' Move the cursor to the end of the bookmark
    Selection.MoveRight Unit:=wdCharacter, Count:=1

    Select Case InsertSpacer
        Case 0
            ' Do nothing. Text inserted immediately
        Case 1
            ' Insert a space
            Selection.TypeText Text:=" "
        Case 2
            'Insert a paragraph mark
            Selection.TypeText Text:=vbCrLf
        Case 3
            'Insert two paragraph marks
            Selection.TypeText Text:=vbCrLf & vbCrLf
    End Select

    ' Insert the text file:
    Selection.TypeText Text:=FileContent
    Exit Sub

Oops:
    Select Case Err.Number
        Case 55 ' File already open
            ' Close the file
            Close #1
            ' Try again
            Resume
        Case 53 ' File not found
            NotFound = "Could not find the file named: " _
            & Chr(34) & TextFile & Chr(34) & vbCrLf _
            & vbCrLf & "Verify the file name and path " _
            & "in the macro code after " _
            & Chr(34) & "Const TextFile As String =" & Chr(34)
            MsgBox NotFound, vbOKOnly
        Case Else
            MsgBox "Error number: " & Err.Number & ", " _
            & Err.Description, vbOKOnly
    End Select
End Sub

Note:

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (12193) 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: Importing a Text File and Inserting after a Bookmark.

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

Viewing Formula Results

When editing information in a cell, you may need to know the result of a portion of your formula. The shortcut described ...

Discover More

Errors when Copying References to External Cells

If you copy a cell that contains a reference to external data, do you get an error? It could be due to the complexity of ...

Discover More

Dynamic Data Based on Chart Changes

Change the data on which a chart is based and Excel obligingly updates the chart to reflect the change. What if you want ...

Discover More

The First and Last Word on Word! Bestselling For Dummies author Dan Gookin puts his usual fun and friendly candor back to work to show you how to navigate Word 2013. Spend more time working and less time trying to figure it all out! Check out Word 2013 For Dummies today!

More WordTips (menu)

MS-DOS with Line Breaks Format in Word 2002 and Word 2003

Finding the built in functionality in Word 2002 & 2003 for saving your document as a MS-DOS format.

Discover More

Removing All File Properties

Want to get rid of any properties you've created for a document? You can do so by using the short macro described in this ...

Discover More

An Automatic File Name

Do you have a set "standard" for how you name new documents? If so, you may be interested in implementing the technique ...

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

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}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. 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 8 + 7?

2019-06-11 04:22:46

Ivan

Hi.

I have a problem.
What if inserted file is located on \\server\folder\file.txt ?
(It's a Linux machine and I can see this file through samba from windows, but Word cannot insert it)


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.

Videos
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.