Word VBA宏插入文件和合并格式化
问题描述:
我有一个页眉/页脚和文本格式的模板。我想编写一个宏来填充此模板的.rtf或.doc文件的内容。另外,我想合并格式,以便保留模板文件的标题和格式,以及.rtf或.doc文件中的图片。Word VBA宏插入文件和合并格式化
剪切粘贴效果很好。如果我打开并保存模板文件,请打开要插入的文件,选择全部,然后使用“合并格式”粘贴特殊文件,然后按照我的意愿获取。我只想要一个更具可扩展性的解决方案。
我写了一个宏,它完成了大部分工作,但它无法合并格式并丢弃(或隐藏)页眉和页脚。我认为正确的方法将使用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,这似乎是使用剪切和粘贴,但结果是一样的。
答
这是我能做的最好的。它以纯文本的形式粘贴,但比没有更好(或粘贴原始格式)。
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
答
我试着在我自己的VBA宏此相同的调用,并发现
Selection.Range.InsertFile(FiletoInsert)
看起来工作时,我只传递一个参数文件名。确保文件名是完整的。
答
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
为什么有人反对票而不当没有其它有效的答案我的回答发表评论我要我自己的问题? – 2014-11-30 18:33:24