G
Greg Maxey
I scrathed together the following today in response to a post in the tables group. I searched Google groups for a similiar solution and since I didn't see anything, I wanted to share it here. As alwasy constructive criticism is welcomed.
Objective is to sort a word table down and accross. Put cursor is table to be sorted and run the following.
Option Explicit
Sub DownAndAccrossTableSorter()
Dim i As Long
Dim j As Long
Dim k As Long
Dim oCell As Cell
Dim oTmpTable As Table
Dim oRng As Word.Range
i = Selection.Tables(1).Range.Cells.Count
'Insert a temporary 1 column/multi-row table at the end of the document
With ActiveDocument.Paragraphs.Last
.Range.Paragraphs.Add
.Range.Tables.Add .Range, i, 1
End With
'Define this table
Set oTmpTable = ActiveDocument.Tables(ActiveDocument.Range.Tables.Count)
'Fill oTmpTable with contents of table to be sorted
For Each oCell In Selection.Tables(1).Range.Cells
With oTmpTable
.Cell(i, 1).Range.Text = Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)
End With
i = i - 1
Next
'Sort
oTmpTable.Sort
'Redefine selected table contents based on sort
With Selection.Tables(1)
For i = 1 To .Range.Columns.Count
For j = 1 To .Range.Rows.Count
k = k + 1
Set oRng = oTmpTable.Cell(k, 1).Range
.Cell(j, i).Range.Text = Left(oRng.Text, Len(oRng.Text) - 2)
Next j
Next i
End With
'Clean up.
oTmpTable.Delete
Set oRng = Nothing
Set oTmpTable = Nothing
End Sub
Objective is to sort a word table down and accross. Put cursor is table to be sorted and run the following.
Option Explicit
Sub DownAndAccrossTableSorter()
Dim i As Long
Dim j As Long
Dim k As Long
Dim oCell As Cell
Dim oTmpTable As Table
Dim oRng As Word.Range
i = Selection.Tables(1).Range.Cells.Count
'Insert a temporary 1 column/multi-row table at the end of the document
With ActiveDocument.Paragraphs.Last
.Range.Paragraphs.Add
.Range.Tables.Add .Range, i, 1
End With
'Define this table
Set oTmpTable = ActiveDocument.Tables(ActiveDocument.Range.Tables.Count)
'Fill oTmpTable with contents of table to be sorted
For Each oCell In Selection.Tables(1).Range.Cells
With oTmpTable
.Cell(i, 1).Range.Text = Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)
End With
i = i - 1
Next
'Sort
oTmpTable.Sort
'Redefine selected table contents based on sort
With Selection.Tables(1)
For i = 1 To .Range.Columns.Count
For j = 1 To .Range.Rows.Count
k = k + 1
Set oRng = oTmpTable.Cell(k, 1).Range
.Cell(j, i).Range.Text = Left(oRng.Text, Len(oRng.Text) - 2)
Next j
Next i
End With
'Clean up.
oTmpTable.Delete
Set oRng = Nothing
Set oTmpTable = Nothing
End Sub