2
votes

I have a template with a header/footer and text formatting. I would like to write a macro to fill this template with the contents of an .rtf or .doc file. Also, I would like to merge the formatting so that I keep the header and formatting from the template file, and the pictures in the .rtf or .doc files.

Cut-and-paste works great. If I open and save the template file, open the file to insert, select all, and paste special with "merge formatting", then I get exactly what I want. I just want a more scalable solution.

I wrote a macro that does most of this, but it fails to merge the formatting and drops (or hides) the header and footer. I thought the correct approach would use the InsertFile method, but I can't figure it out.

Any pointers would be appreciated (I'm new to both Word and VBA).

Sub InsertFile()

    currentPath = ActiveDocument.Path

    Set FileBox = Application.FileDialog(msoFileDialogFilePicker)

    With FileBox
        .Title = "Select the File that you want to insert"
        .InitialFileName = currentPath & "\" & "*.rtf"
        .AllowMultiSelect = False
        If .Show = -1 Then
            FiletoInsert = .SelectedItems(1)
        End If
    End With

    Selection.Range.InsertFile FiletoInsert
    Set FileBox = Nothing
End Sub

Update - I also tried this approach, which seems to use cut-and-paste, but the results are the same.

3

3 Answers

1
votes

Here's the best that I can do. It pastes as plain text, but that's better than nothing (or pasting with original formatting).

Sub InsertFile()
    ' inserts selected file into current document (strips formatting)

    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .Title = "Select the File that you want to insert"
        .Show
        FiletoInsert = .SelectedItems(1)
    End With

    ' get content from my file
    Application.Documents.Open (FiletoInsert)
    Application.Selection.WholeStory
    Application.Selection.Copy
    Application.ActiveWindow.Close

    ' paste without formatting
    Application.Selection.PasteSpecial DataType:=wdPasteText

End Sub
1
votes
Sub InsertFile()

    ' inserts selected file into current document (strips formatting)

    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .Title = "Select the File that you want to insert"
        .Show
        FiletoInsert = .SelectedItems(1)
    End With
    Selection.InsertFile FileName:=FiletoInsert, Range:="", _
        ConfirmConversions:=False, Link:=False, Attachment:=False
End Sub
0
votes

I've tried this same call in my own VBA macro, and find that

Selection.Range.InsertFile (FiletoInsert)

Seems to work when I only pass the one parameter filename. Make sure the filename is complete.