Inserting tables into a word via vb.net

I am making an addon for a word. It should be possible to insert tables. Dimensions and location should be indicated. When I insert the first table it works fine, but if I insert another table then the first table is deleted and the new one is inserted. I'm still pretty new to vb.net, so the code might not be the best.

    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

      

+3


source to share


1 answer


Assuming you are using the above code to add both tables (perhaps in a loop), I think the problem is that you are overwriting the first table from the second since you are using the same range.

The documentation for Tables.Add says:

The range in which the table should be displayed. The table replaces the range if the range is not collapsed.

If you change the first line of your code to:

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

      

to something like

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

      



And after you've added your first table, follow these steps:

range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);

      

It should allow you to add both tables.

However, if you add two tables right after each other, I think Word is concatenating them into one table, so you need to add a spacing between them, for example using something like:

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

      

I think it might work.

+3


source







All Articles