loop through all tables in a document

T

TonyLogan

If I have a variable number of tables in a document, how can I loop through all the tables, with the goal being to find each table, perform some cleanup or find/replace functions within each table, find the next table, etc., until the end of the document?

I can write the code to do the clean-up and find/replace stuff, but I can't figure out how to find each table and stop at the end of the document.

Thanks.
 
P

Pat Garard

G'Day Tony,

Sub IterateThroughTables()
Dim intX As Integer
With ActiveDocument
For intX = 1 To .Tables.Count
.Tables(intX).Select
'
' Do your Stuff Here
'
Next
End With
End Sub

--
Regards,
Pat Garard
Australia

Anne & Pat Garard.
apgarardATbigpondDOTnetDOTau
_______________________________________________
 
J

Jay Freedman

Pat Garard said:
G'Day Tony,

Sub IterateThroughTables()
Dim intX As Integer
With ActiveDocument
For intX = 1 To .Tables.Count
.Tables(intX).Select
'
' Do your Stuff Here
'
Next
End With
End Sub

While that will work, it can get slower than molasses if the tables
are large and/or there are a lot of them. There are two issues: First,
using a numerical index to access ActiveDocument.Tables(intX) forces
Word to count through all the tables from 1 to intX each time, which
is a waste of time if intX is in the hundreds. Second, using .Select
and then working on the Selection forces Word to scroll to the table
and redraw the screen, which is a very processor-intensive operation.

To avoid both issues, code like this is preferable:

Sub IterateThroughTablesFaster()
Dim aTable As Table
Dim aRange As Range

For Each aTable In ActiveDocument.Tables
Set aRange = aTable.Range
'
' Do your Stuff Here with aRange
'
Next aTable

Set aRange = Nothing ' clean up
Set aTable = Nothing

End Sub
 
P

Pat Garard

Yaaaaaaaassssssssssssssssssssss!
--
Regards,
Pat Garard
Australia

Anne & Pat Garard.
apgarardATbigpondDOTnetDOTau
_______________________________________________
 
P

Pat Garard

Why don't we let him cut his teeth on
WITH
and
FOR
and leave COLLECTIONS for another day!
--
Regards,
Pat Garard
Australia

Anne & Pat Garard.
apgarardATbigpondDOTnetDOTau
_______________________________________________
 

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