Vba – Word VBA macro to insert file and merge formatting

ms-wordvba

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.

Best Solution

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
Related Question