0
votes

nested table in WordI have a template which is essentially a 4-row column in Work. Each cell marked with a bookmark. I've copied a table from Excel to Word into one of these bookmarks (inside on of the cells). Now I'm trying to format this 'nested table' to make it fit according to my desired column widths (for certain columns) but I'm really struggling with the syntax. Additionally, in the table, the first row contains some merged cells (Some are merged to the cell in the adjacent column and some in the row below).

The code I was trying:

With wd.Tables(2)
    .Columns(2).Width = 20
End With

But I keep getting "Run-time error '5941': The requested member of the collection does not exist." Does this mean I am not indexing it properly?

Tabels(2) is meant to refer to the 'nested table' within the larger single column of 4 rows cells.

How do index it properly/find its index? And how would I change the widths when I have merged cells? Would I need to: divide them first>adjust width>re-merge? Also, I'm doing this in VBA Word, if I reference 'Microsoft Word xx.0 Object Library' in excel VBA can I do this in excel?

1
Indexes begin at 0, not 1, so they are always one less than the number you'd expect the object to be. For example for the second Table in your Word document you would actually need to reference wd.Tables(1), the first Table in your Word document would be wd.Tables(0).Jordan
@Jordan are you sure? I just ran a check where I had two tables (one below the other, i.e. not nested) with one set as 'Tables(0)' and I got the same run-time error. When set them to Tables(1) and Tables(2) it worked fineJoshD
@Jordan wrong. In Word, the indexes of objects like Tables, Rows, Columns etc. begin with 1 ot 0. Same in other Office apps. If this truly is a nested table I would rather suspect you need to access wd.Tables(1).Tables(1) instead of wd.Tables(2)LocEngineer
@LocEngineer, I tried that but now I get: Run-time error 'The requested member of the collection does not exist' and highlights the 'With' lineJoshD
Could you add a screenshot of your table, anonymized? Just to see the structure?LocEngineer

1 Answers

1
votes

I have recreated a nested table like the one in the screen shot; i.e. 1 column with 4 rows, then a nested 14 column/10 row table in row 3.

The following code works just fine for me:

Sub AccessNestedTable()
Dim tbl As Table, tbl2 As Table
Dim wd As Document

Set wd = ActiveDocument

Set tbl = wd.Tables(1)
Set tbl2 = tbl.Tables(1)

With tbl2
    .Columns.Width = 20
End With

End Sub