通过 vb.net 将表格插入 word

Insert tables into word via vb.net

我正在为 word 制作插件。必须可以插入 tables。应该可以指定尺寸和位置。当我插入第一个 table 时它工作正常,但如果我插入另一个 table,那么第一个 table 被删除并插入新的。我对 vb.net 还是很陌生,所以代码可能不是最好的。

    With Globals.WordAddIn.ActiveDocument.Tables.Add(Globals.WordAddIn.ActiveDocument.Range, 1, 1)
        .TopPadding = 0
        .BottomPadding = 0
        .LeftPadding = 0
        .RightPadding = 0
        .Rows.WrapAroundText = True
        .Rows.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage
        .Rows.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage
        .Rows.HorizontalPosition = dobHorizontal
        .Rows.VerticalPosition = dobVertical
        .Rows.Height = dobHeight
        .Columns.Width = dobWidth
    End With

假设您正在使用上面的代码添加两个 table(可能在一个循环中)我认为问题在于您正在用第二个 table 覆盖第一个 table 因为你使用相同的范围。

Tables.Add 的文档说:

The range where you want the table to appear. The table replaces the range, if the range isn't collapsed.

如果您更改代码的第一行:

With Globals.WordAddIn.ActiveDocument.Tables.Add(Globals.WordAddIn.ActiveDocument.Range, 1, 1)

类似于

dim range = Globals.WordAddIn.ActiveDocument.Range;
With Globals.WordAddIn.ActiveDocument.Tables.Add(range, 1, 1)

然后在您添加第一个 table 之后,您可以:

range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);

它应该让你添加两个 tables。

但是,如果你在彼此之后添加两个 table,我认为 Word 将它们合并为一个 table,因此你需要在它们之间添加一些 space,例如通过使用类似的东西:

range.InsertParagraphAfter();
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd); ' need to collapse again to avoid overwriting

我认为它可能有效。