使用vba将word文档的内容复制到另一个word文档中

时间:2014-01-23 19:45:30

标签: vba word-vba

我已经多年没用过VB了,所以如果事实证明这很明显,请原谅我。我正在尝试编写一个单词vba宏,用于显示userform的模板,然后根据userform导入fileA.docx,fileB.docx或fileC.docx的内容。 (之后我将使用书签填写一些表格数据,我不知道这是否相关)。文件A,B和C将包含带有一些基本格式的文本,例如列表,但没什么特别的。

我在网上看到的解决方案可以将文件内容复制到一个新文件,但理想情况下我想将其中一个文件导入到我从模板中获取的新的,当前未命名的文件中。我想我遇到的问题是将选择切换到其中一个文件,然后再回到新的未命名文档,尽管我可以用一只手来确保我也正确地复制。


更新:我做的事情太难了,虽然这里的答案让我指出了正确的方向(谢谢!)。最后我刚刚做了

ThisDocument.Activate

Selection.InsertFile("fileA")

它给了我想要的所有东西的原始转储。

5 个答案:

答案 0 :(得分:6)

使用这些命令可以在您正在使用的文档与复制和粘贴元素之间切换:

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

然后您可以进行格式化,或者使用之前的原始格式复制和粘贴它们。

答案 1 :(得分:2)

录制宏...

  1. 从源文档开始
  2. 按ctrl-a选择所有内容
  3. 按ctrl-c将其复制到剪贴板
  4. 切换到目标文档
  5. 按ctrl-v粘贴到文档
  6. 停止录制
  7. 或(假设单词2007或更高版本)

    1. 在源文档关闭的情况下从目标文档开始
    2. 在功能区上点击插入>对象>文件中的文字......
    3. 导航至源文档
    4. 点击插入按钮
    5. 停止录制
    6. 我更喜欢第二个版本,所以我应该把它放在第一个

答案 2 :(得分:1)

(我认为)这是您要加入的一项重大改进,因为:

  1. 不使用剪贴板,因此不会使您的宏容易受到用户在宏运行时更改剪贴板内容的攻击
  2. 不使用文件,因此消除了I / O,从而大大提高了速度,并消除了必须处理文件系统安全性/权限等的潜在问题。如果在文档之间循环,请不要使用.InsertFile()你会放慢自己的速度。最后,仅在必要时使用一次。下面的示例显示了如何在不使用.InsertFile()的情况下实现相同的结果

想法是将在1个源文档中找到的部分文本传输到与源文档不同的目标文档中,并保持源格式。

要完成上述操作(跳过代码以打开文档):

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

答案 3 :(得分:0)

我正在做同样的事情,试图选择其他文件,复制并粘贴。但它没有用(我收到错误可能是因为其他一些应用程序正在使用剪贴板,但我不确定。)。所以我做了一点搜索,在Microsoft开发中心找到了完美的解决方案。

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

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

答案 4 :(得分: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