Sorting Multiple Tables

Joined
Apr 14, 2023
Messages
1
Reaction score
0
Is there a way to sort multiple tables with Word 2010? Not the rows within the tables, but all the tables individually by table name - putting the tables in alphabetical order, using the first row/cell in a table, or some other field. I do not want the tables to be merged. There are 20 individual tables and I could easily do this manually at this point, but the number of tables will be increasing considerably and they may need to be rearranged for different purposes.
 
Joined
Mar 26, 2023
Messages
4
Reaction score
0
Sub SortTableByTitle()
Dim varTableKeys() As Variant
Dim varTemp As Variant
Dim lngIndex As Long, lngCompB As Long, lngCompA As Long
With ActiveDocument
ReDim varTableKeys(1 To .Tables.Count)
For lngIndex = 1 To .Tables.Count
'If the tables are actually titled i.e., .title property set to a text value, use:
varTableKeys(lngIndex) = .Tables(lngIndex).Title
'If you are depending on a cell content value as the title e.g., The first cell, use something like this:
'varTableKeys(lngIndex) = Trim(Left(.Tables(lngIndex).Cell(1, 1).Range.Text, Len(.Tables(lngIndex).Cell(1, 1).Range.Text) - 2))
Next
End With
'Sort the array\reposition tables
For lngIndex = LBound(varTableKeys) To UBound(varTableKeys) - 1
lngCompA = lngIndex
For lngCompB = lngIndex + 1 To UBound(varTableKeys)
If varTableKeys(lngCompB) < varTableKeys(lngCompA) Then lngCompA = lngCompB
Next
If lngCompA > lngIndex Then
'Swap table position in document
Swap_Posit lngIndex, lngCompA
'Swap position in array
varTemp = varTableKeys(lngIndex)
varTableKeys(lngIndex) = varTableKeys(lngCompA)
varTableKeys(lngCompA) = varTemp
End If
Next lngIndex
lbl_Exit:
Exit Sub
End Sub

Sub Swap_Posit(ByVal lngPositA As Long, ByVal lngPositB As Long)
'Swops position of two indexed tables in active document.
Dim oTblA As Table, oTblB As Table
Dim oRngA As Range, oRngB As Range, oRngTgt As Range
Dim lngIndex As Long
Set oTblA = ActiveDocument.Tables(lngPositA)
Set oTblB = ActiveDocument.Tables(lngPositB)
Set oRngA = oTblA.Range
Set oRngB = oTblB.Range
oRngA.Next.InsertBefore vbCr
Set oRngTgt = oRngA.Next.Next
oTblB.Range.Cut
oRngTgt.Collapse wdCollapseStart
oRngTgt.Paste
'Move the first table to the last position of second table
oTblA.Range.Cut
oRngB.Collapse wdCollapseStart
oRngB.Paste
oRngA.Delete
lbl_Exit:
Exit Sub
End Sub
 

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