将多个嵌套表复制并粘贴到特定的Word表单元格中

时间:2019-06-28 07:10:53

标签: excel vba ms-word

我已使用WordEditor在Outlook模板中创建表,并计划将Excel工作簿的多个范围复制并粘贴为该表的特定单元格中的嵌套表-想法是每次创建一个新表时粘贴到此单元格中,所有现有表都被推开(我可以在以后找到表的位置)。

我打算使用书签来粘贴范围,但对表示法不熟悉,并且很难在网络上找到任何相关文档

Dim wdDoc As Word.Document
Dim ws_sum, ws As Worksheet
Dim tblSess As Word.Table
......

......
With ws_sum
    wdDoc.Bookmarks.Add Name:="tab", Range:=tblSess.cell(2, 1).Range
    .Range(.Cells(9, 3), .Cells(12, 7)).Copy
    wdDoc.Bookmarks("tab").Range.PasteAsNestedTable
    .Range(.Cells(24, 2), .Cells(31, 10)).Copy
    wdDoc.Bookmarks("tab").Range.PasteAsNestedTable
......
End With

我遇到的问题是,当前每次粘贴新的嵌套表时,它都会完全删除加标签的单元格的内容。我尝试通过将'Range:= tblSess.cell(2,1).Range'替换为'Range:= tblSess.cell(2,1).Range(0,0)'来指定单元格的第一个条目,但这会抛出运行时出现错误。还有另一种方法吗?

1 个答案:

答案 0 :(得分:0)

当然有多种方法可以解决此问题。无论如何,关键是

  • 确保单元格的开头有一个空白的段落标记。这样可以提供下一个插入位置,以免最终嵌套在另一个粘贴表中。
  • 使用Range对象。我更喜欢两个:一个作为单元格的开始,另一个作为粘贴目标。

以下代码段基于问题中的代码进行了说明:

Dim rngCellStart As Word.Range, rngTarget As Word.Range

Set rngTarget = tblSess.Cell(2, 1).Range
rngTarget.Collapse wdCollapseStart
Set rngCellStart = rngTarget.Duplicate

'put a paragraph mark before the table that is pasted
rngTarget.InsertBefore vbCr
'Move the target Range to leave out that paragraph
rngTarget.MoveStart wdCharacter, 1

'may no longer be needed... but could be used to mark
'the starting point of the cell as that is where it stays
'wdDoc.Bookmarks.Add Name:="tab", Range:=rngCellStart

.Range(.Cells(9, 3), .Cells(12, 7)).Copy
rngTarget.PasteAsNestedTable

'Following paste actions for additional tables.
'Could be put in a separate procedure and called in a loop
rngCellStart.InsertBefore vbCr
Set rngTarget = rngCellStart.Duplicate
rngTarget.Collapse wdCollapseEnd
.Range(.Cells(24, 2), .Cells(31, 10)).Copy
rngTarget.PasteAsNestedTable