簡體   English   中英

使用vba將word文檔的內容復制到另一個word文檔中

[英]Using vba to copy the contents of a word document into another word document

我已經多年沒用過VB了,所以如果事實證明這很明顯,請原諒我。 我正在嘗試編寫一個單詞vba宏,用於顯示userform的模板,然后根據userform導入fileA.docx,fileB.docx或fileC.docx的內容。 (之后我將使用書簽填寫一些表格數據,我不知道這是否相關)。 文件A,B和C將包含帶有一些基本格式的文本,例如列表,但沒什么特別的。

我在網上看到的解決方案可以將文件內容復制到一個新文件,但理想情況下我想將其中一個文件導入到我從模板中獲取的新的,當前未命名的文件中。 我認為我遇到問題的地方是將選擇切換到其中一個文件,然后再回到新的未命名文檔,盡管我可以用一只手來確保我也正確地復制。


更新:我做的事情太難了,雖然這里的答案讓我指出了正確的方向(謝謝!)。 最后我才做到了

ThisDocument.Activate

Selection.InsertFile("fileA")

這給了我想要的一切原始轉儲。

使用這些命令可以在您正在使用的文檔和復制和粘貼元素之間切換:

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. 按ctrl-a選擇所有內容
  3. 按ctrl-c將其復制到剪貼板
  4. 切換到目標文檔
  5. 按ctrl-v粘貼到文檔中
  6. 停止錄音

或(假設單詞2007或更高版本)

  1. 在源文檔關閉的情況下從目標文檔開始
  2. 在功能區上單擊插入>對象>文件中的文本...
  3. 導航到源文檔
  4. 單擊插入按鈕
  5. 停止錄音

我更喜歡第二個版本所以我應該把它放在第一位

這是一個重要的改進(我認為)你想要合並,因為它:

  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

我正在做同樣的事情,試圖選擇其他文件,復制和粘貼。 但它沒有用(我收到錯誤可能是因為其他一些應用程序正在使用剪貼板,但我不確定。)。 所以我做了一些搜索,在Microsoft Dev Center上找到了完美的解決方案。

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

Selection.Collapse Direction:=wdCollapseEnd 
Selection.InsertFile FileName:="C:\TEST.DOC"
'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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM