gpt4 book ai didi

vba - 追加而不是替换 Word 文档内容

转载 作者:行者123 更新时间:2023-12-03 01:51:54 24 4
gpt4 key购买 nike

我的 Excel 工作簿中有多个工作表。我在循环中进行迭代,复制数据范围并将它们粘贴到 word 中。

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

那么如何停止替换之前的内容并让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

最佳答案

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

关于vba - 追加而不是替换 Word 文档内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39225074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com