What is the quickest way to copy a table to an array?

S

stephenc

Hi everyone,

I have a table to process. It can vary in size between 2-4 columns and 2-100
rows. The table is a simple thing, containing just plain text.

What is the quickest/nicest way to copy the content of the table to a 2D
array?

Stephenc
 
J

Jay Freedman

stephenc said:
Hi everyone,

I have a table to process. It can vary in size between 2-4 columns
and 2-100 rows. The table is a simple thing, containing just plain
text.

What is the quickest/nicest way to copy the content of the table to a
2D array?

Stephenc

I would do this in three stages:

1. Convert the table to text, with tabs separating the cells in each row and
paragraph marks separating the rows. This makes the method independent of
the number of rows or columns. The drawback is that if the table contains
split or merged cells, you lose that information.

2. Use the Split function with the paragraph mark (vbCr) separator character
to assign the rows to a temporary Variant variable -- essentially a 1D
array.

3. Use the Split function with a tab (vbTab) separator character to assign
each row of the temporary array to one member of an array of Variants.

Sub demo()
Dim tempArray As Variant
Dim finalArray() As Variant
Dim oTbl As Table
Dim oRg As Range
Dim i As Long

If ActiveDocument.Tables.Count < 1 Then Exit Sub

Set oTbl = ActiveDocument.Tables(1)
Set oRg = oTbl.ConvertToText(Separator:=vbTab)

' load each row of former table
' into one member of tempArray, with the
' tab characters still in place
tempArray = Split(oRg.Text, vbCr)

ActiveDocument.Undo ' restore the table

' make as many "rows" in finalArray
' as there are in tempArray
ReDim finalArray(UBound(tempArray))

' transfer each row of tempArray into
' a sub-array of finalArray, separating at tabs
For i = 0 To UBound(tempArray)
finalArray(i) = Split(tempArray(i), vbTab)
Next

' display one specific cell's contents
MsgBox finalArray(2)(2)
End Sub

I haven't done any timing runs, but I think this will run faster than nested
loops that extract the individual cell contents column by column and row by
row.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 

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