使用VBA将一个Word文档的内容复制到另一个Word文档中

13

我已经好多年没有使用VB了,如果这个问题变得明显,请原谅我。我正在尝试编写一个Word VBA宏,用于模板中显示用户窗体,然后根据用户窗体导入fileA.docx、fileB.docx或fileC.docx的内容(之后我将使用书签填写一些表单数据,不知道这是否相关)。文件A、B和C将包含一些基本格式(如列表),但没有什么花哨的东西。

我在网上看到的解决方案可以将文件的内容复制到新文件中,但理想情况下,我希望将其中一个文件的所有内容导入到我从模板中获取的新的未命名文件中。我认为我遇到问题的地方是将选择切换到这些文件之一,然后切回新的未命名文档,虽然我也需要帮助确保我正在正确地复制文件。


更新:我把事情想得太难了,虽然这里的答案让我朝着正确的方向前进(谢谢!)。最终我只需执行以下操作:

ThisDocument.Activate

Selection.InsertFile("fileA")

它给了我我想要的每一件事情的原始转储。

5个回答

8
使用这些命令,你可以在不同的文档之间切换并复制粘贴元素:
ThisDocument.Activate 'Sets the main document active
Documents("Name.doc").Activate 'Activates another document

您可以使用复制命令将内容插入、复制和粘贴到文档中。

ThisDocument.Range.InsertAfter("String") 'Insert text

Selection.WholeStory 'Select whole document
Selection.Expand wdParagraph 'Expands your selection to current paragraph
Selection.Copy 'Copy your selection
Documents("name.doc").Activate 'Activate the other document
Selection.EndKey wdStory 'Move to end of document
Selection.PasteAndFormat wdPasteDefault 'Pastes in the content

您可以对其进行格式化,或者从以前的格式中复制并粘贴它们。


4
这里有一个重要的改进(我认为)你会想要包含,因为它:
  1. 不使用剪贴板,因此不会让您的宏在运行时受到用户更改剪贴板内容的影响
  2. 不使用文件,因此通过消除I/O大大提高了速度,并消除了处理文件系统安全/权限等潜在问题的风险。如果您正在遍历文档,不要使用.InsertFile(),否则您会减慢自己的速度。仅在必要时,在结尾使用一次。下面的示例显示了如何在不使用.InsertFile()的情况下完成相同的结果。

思路是将源文档中找到的某些文本部分转移到与源文档不同的目标文档,并保留源格式。

为了实现以上目标(跳过打开文档的代码):

For Each oTable In oDoc_Source  
'the above could have been anything that returns a Range object
'such as: ActiveDocument.Content.Find.Execute ....

'...
'logic here to identify the table, or text, you are looking for
'...

'I can't believe the MS Dev Center folks could only think
'of .InsertFile(), which is the last resort I would go for, 
'especially if your code runs on a web server [concurrent web requests]!

'SAFEST
'(no user interference on clipboard possible, no need to deal with file i/o and permissions)
'you need a reference to Document.Content, 
'as the act of obtaining a reference "un-collapses" the range, so the below 3 lines must be in that order.
Set oRange =  oDoc_DestinationDoc.Content
oRange.Collapse Direction:=wdCollapseEnd
oRange.FormattedText = oTable.Range

'BRUTE, AND PRONE TO RANDOM ERRORS AND HANGS DUE TO USER INTERFERENCE WITH CLIPBOARD 
'find a way to implement WIHTOUT using the CLIPBOARD altogether to copy the below range object
'it will be easier for PC users to use the clipboard while the macro runs
'and it will probably be safer for the output of this macro to remain uncorrupted

'oTable.Range.Copy
'Set oRange =  oDoc_DestinationDoc.Content
'oRange.Collapse Direction:=wdCollapseEnd
'oRange.Paste


'THE BELOW DOES NOT WORK
' '1) - cannot add a range from another document
' 'adds only text, not the formats and not the table layout
' oTable.Range.TextRetrievalMode.IncludeFieldCodes = True
' oTable.Range.TextRetrievalMode.IncludeHiddenText = True
'  oDoc_DestinationDoc.Content.InsertAfter oTable.Range
'
' '2) - cannot add a range from another document
'  oDoc_DestinationDoc.Content.Tables.Add oTable.Range, iRowMax, iColMax
' 
' '3) - only puts in plain text, and it replaces the range without the .Collapse call
'  oDoc_DestinationDoc.Content.Text = oTable.Range

1
感谢您指出FormattedText属性!(SelectionRange - cxw
不确定这是否是一个问题,但是没有必要进行选择。只需使用2个范围对象及其.FormattedText属性即可。用户的选择不会被不必要地更改。如果我可以补充一下,下面来自Andras Kovacs的帖子正在传播关于如何使用.InsertFile()函数的误导信息。请阅读我的完整帖子以了解为什么要尽量减少使用该函数。 - Fr4nc01s

2

记录宏...

  1. 在源文件中开始
  2. 按Ctrl+A选择全部内容
  3. 按Ctrl+C将其复制到剪贴板中
  4. 切换到目标文件
  5. 按Ctrl+V将其粘贴到文件中
  6. 停止录制

或者(假设Word 2007或更高版本)

  1. 在目标文档中开始,源文件关闭
  2. 在功能区中单击插入>对象>从文件中的文本...
  3. 导航到源文件
  4. 单击插入按钮
  5. 停止录制

我更喜欢第二个版本,所以应该把它放在第一个位置


这个能否集成到我的用户窗体的vba脚本中?关键是我需要根据用户输入选择要转储到当前文档中的文件。我想避免将用户窗体代码复制到每个文件A、文件B等中以填充字段。 - user3229306
是的。任何您记录为宏的内容最终都会成为VBA,并且可以将其粘贴到逻辑中并修改以使用变量而不是硬编码名称。在VBA IDE中打开Normal> Modules> NewMacros,您将看到它。如果您在开始录制宏时命名宏,则会更有帮助。 - casgage

0
'set current doc name and path
    Dim docName As String: docName = ActiveDocument.name
    Dim filepath As String: filepath = ActiveDocument.Path
'create a new file
    Documents.Add
'get the path of a current file
    ChangeFileOpenDirectory filepath
'insert content of current file to newly created doc
    Selection.InsertFile _
        FileName:=docName, _
        Range:="", _
        ConfirmConversions:=False, _
        Link:=False, _
        Attachment:=False
'open prompt to save a new file
    With Dialogs(wdDialogFileSaveAs)
        .name = docName & "-copy"
        .Show
    End With

0
我也曾经尝试过选择其他文档,然后复制和粘贴。但是它并没有起作用(我收到了一个错误,可能是因为其他应用程序正在使用剪贴板,但我不确定)。所以我进行了一些搜索,在微软开发中心找到了完美的解决方案。

https://msdn.microsoft.com/en-us/vba/word-vba/articles/selection-insertfile-method-word

Selection.Collapse Direction:=wdCollapseEnd 
Selection.InsertFile FileName:="C:\TEST.DOC"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接