Sorting Data in a Word Table

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

To sort the data in a Word table by using VBA, use the Sort method of the Table object to specify how the table should be sorted. You can specify up to three fields (columns) on which to sort. For each field participating in the sort operation, you can specify the data type of the field (numeric, alphanumeric, date, and so on) and the sort order for the field (ascending or descending). The following procedure sorts data in a single column of a table.

Sub SortSingleColumn(tblTable As Word.Table, _
                     strFieldNum As String, _
                     lngSortFieldType As WdSortFieldType, _
                     lngSortOrder As WdSortOrder)
   ' Sort on a single column of a table.

   With tblTable
      ' Select table.
      .Select
      ' Sort as specified.
      .Sort ExcludeHeader:=True, FieldNumber:=strFieldNum, _
         SortFieldType:=lngSortFieldType, _
         SortOrder:=lngSortOrder
   End With
End Sub

The SortSingleColumn procedure can be found in the ThisDocument module in SortTable.doc, which is available in the ODETools\V9\Samples\OPG\Samples\CH15 subfolder on the Office 2000 Developer CD-ROM.