Friday, 19 February 2010

Read a Word table in VBA - or not!

To read data from a WORD table using a macro you might think you could use something like

Tables(1).Rows(1).Cells(1)

This is great because each collection (Rows and Cells) has a count property. Unfortunately you'd be wrong - sometimes. If you've merged adjacent cells vertically anywhere in the table you can no longer use the rows collection for that table. So you might try to loop over all rows and columns using

Tables(1).Cell(1,1)

but when you reach the second of the merged cells you get error 5941 "the requested element does not exist". The merged cell can only be addressed by its top left co-ordinate. Also, there's no way to count the rows and columns in the table (because you can't access the rows collection).

You can read successive cells by selecting the top left cell  then using

Selection.MoveRight wdCell, 1

but I can't find a way to limit the operation to the table - if you select a cell beyond the last cell the table grows by one row. There doesn't seem to be a simple count for the number of cells. Also, the merged cell may appear multiple times in this enumeration, once for each row of cells that was merged.

So, how to enumerate the cells of a Word table? The only way I can find is to use the cell(row,column) method with wildly excessive row and column limits, then handle the errors. Note that even this isn't neat, the error for running off the edge of the table is the same as that for hitting a merged cell.

Sub numbercells()
    On Error Resume Next
    For iRow = 1 To 100
        For iCol = 1 To 100
            ActiveDocument.Tables(1).Cell(iRow, iCol).Range.Text = _
                Format(iRow, "0") & ", " & Format(iCol, "0")
        Next iCol
    Next iRow
End Sub

If you know better, let me know.

No comments: