用于插入文件和合并格式的 Word VBA 宏 [英] Word VBA macro to insert file and merge formatting

查看:98
本文介绍了用于插入文件和合并格式的 Word VBA 宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

任何指针将不胜感激(我是 Word 和 VBA 的新手).

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.

推荐答案

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

这篇关于用于插入文件和合并格式的 Word VBA 宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆