附加而不是替换Word文档内容

时间:2016-08-30 10:30:31

标签: excel vba excel-vba

我在Excel工作簿中有多个工作表。我在循环中迭代,在那里我复制数据范围并将它们粘贴到单词中。

问题是每次将工作表的内容复制并粘贴到单词时,之前的所有内容都会消失。

那么如何才能停止替换以前的内容并将VBA脚本附加到word文档?

Sub ewc()

    Dim WordApp As Word.Application
    Dim myDoc As Word.Document
    Dim WordTable As Word.Table
    Dim ws As Worksheet
    Dim tbl As ListObject

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Set WordApp = GetObject(class:="Word.Application")

    WordApp.Visible = True
    WordApp.Activate

    Set myDoc = WordApp.Documents.Open("D:\asd.docx")

    For Each ws In ThisWorkbook.Worksheets
        Debug.Print ws.Name, ThisWorkbook.Worksheets.Count

        ws.UsedRange.Activate
        LastRow = StartCell.SpecialCells(xlCellTypeLastCell).Row
        LastColumn = StartCell.SpecialCells(xlCellTypeLastCell).Column
        Debug.Print LastRow, LastColumn

        ws.Range(StartCell, ws.Cells(LastRow, LastColumn)).Select
        myDoc.Content.Paste

        Set WordTable = myDoc.Tables(1)
        WordTable.AutoFitBehavior (wdAutoFitWindow)
        myDoc.Save


EndRoutine:
        Application.ScreenUpdating = True
        Application.EnableEvents = True

'Clear The Clipboard
        Application.CutCopyMode = False
    Next ws
End Sub

1 个答案:

答案 0 :(得分:4)

myDoc.Content.Paste取代myDoc.Content中的所有内容。

  

If you don't want to replace the contents of the range, use the Collapse method before using this method.

由于您无法折叠myDoc.Content,因此您需要自定义范围对象

Dim pasteRange as Word.Range
'...
Set pasteRange = myDoc.Content
pasteRange.Collapse wdCollapseEnd
pasteRange.Paste