Word VBA宏插入文件和合并格式

时间:2013-05-11 23:04:32

标签: vba ms-word word-vba

我有一个带页眉/页脚和文本格式的模板。我想编写一个宏来填充此模板与.rtf或.doc文件的内容。此外,我想合并格式,以便我保留模板文件中的标题和格式,以及.rtf或.doc文件中的图片。

剪切和粘贴效果很好。如果我打开并保存模板文件,打开要插入的文件,选择全部,然后粘贴特殊的"合并格式化",然后我得到我想要的。我只想要一个更具伸缩性的解决方案。

我编写了一个宏来完成大部分工作,但它无法合并格式并删除(或隐藏)页眉和页脚。我认为正确的方法会使用InsertFile方法,但我无法弄清楚。

任何指针都会受到赞赏(我对Word和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

更新 - 我也试过this approach,它似乎使用剪切和粘贴,但结果是一样的。

3 个答案:

答案 0 :(得分:1)

这是我能做的最好的事情。它粘贴为纯文本,但这比没有更好(或粘贴原始格式)。

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 :(得分:1)

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

答案 2 :(得分:0)

我已经在我自己的VBA宏中尝试了同样的调用,并找到了

Selection.Range.InsertFile(FiletoInsert)

当我只传递一个参数文件名时似乎工作。确保文件名已完成。

相关问题