Extracting a value from a word table

S

Simon Forer

Hi, I have a word document with 4 tables.

I’m wanting to extract the values from the last row in the third table
to calculate a total and then use that total in a paragraph.

The last row of the table always starts with “Grand Total:” in column
1, but the row number is variable.

I want the values of columns 2, 4 and 7.

(I’m using Word 2010)

Can show you our code, but it doesnt work...can anyone help?
 
T

That Guy

The best way to do this, also the most processor intensive, is to loop
through every cell of every table then grab the columns based on the
row that you find the text in.

Now I suspect that you may be already doing something like this but if
you are searching for text in a table you need to remember that more
that just that text is going to be present in each table cell. You
will need to search for whatever text you are looking for plus
characters 13 and 7 in that order.

you could use the following:

Private Sub temp()
Dim aTable As Table
Dim aCell As Cell
Dim values(3) As Integer

For Each aTable In ActiveDocument.Tables
Set aCell = aTable.Cell(1, 1)
Do
If StrComp(aCell.Range, "Grand Total:" & Chr(13) &
Chr(7),_
vbTextCompare) = 0 Then

values(0) = aTable.Cell(aCell.Row.Index, 2)
values(1) = aTable.Cell(aCell.Row.Index, 4)
values(2) = aTable.Cell(aCell.Row.Index, 7)
End If
Set aCell = aCell.Next
Loop Until aCell Is Nothing
Next aTable

End Sub

A more optimized way to do this if your tables are very large or
across a number of pages would be to do a kind of binary sort on the
document. Search the document for the 'Grand Total' text based on it
being in the first or second half. Keep doing this until you know
roughly the page it is on. Then go to that page and start from the
cells there. This is much more involved and should only be undertaken
if you are dealing with pages upon pages.

Hope that helps.
 
D

dedawson

Or, if you know what you want will always be in columns 2, 4 and 7 of
the the last row of the third table, you could simply go get the
values without all the looping:

Dim ThirdTable As Table
Dim value1, value2 As Integer
Set ThirdTable = ActiveDocument.Tables(3)
iLastRow = ThirdTable.Rows.Count
value1 = Left(ThirdTable.Rows(iLastRow).Cells(2).Range.Text,
Len(ThirdTable.Rows(iLastRow).Cells(2).Range.Text) - 2)
value2 = Left(ThirdTable.Rows(iLastRow).Cells(3).Range.Text,
Len(ThirdTable.Rows(iLastRow).Cells(3).Range.Text) - 2)
Total = value1 + value2

The Left(... Len(...) -2) construct is required to discard the End-of-
Cell markers and return only the cell's value
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top