Use a macro to sort when the property you want to use is
not available in the sort window.
Before you begin
Note: This topic applies only to templates that are generated
into Microsoft Word documents.
About this task
The benefits of using a macro to sort:
- The macro can run on any table in the template.
- If any table uses the <RPE_SORT> comment
in it, that table is sorted.
- Tables that do not use the <RPE_SORT> comment
are not sorted.
- The <RPE_SORT> comment can be deleted
from the final output.
Procedure
- Add a macro label on the columns to be sorted:
- Open the template in the Document Studio application.
- In the header cell of the column to sort on, add a
Comment
element.
- Double-click the Comment element and enter <RPE_SORT>.
- Repeat on each table in the template to update.
- Create the macro:
- Open Microsoft Word.
- Copy and paste the following script into the file:
' Macro: sort tables
' This macro is provided as is with no implicit or explicit support from IBM.
Sub sortTables()
Dim tbl As Table
' sort each table
For Each tbl In ActiveDocument.Tables
' determine if the table has header
Dim hasheader As Boolean
hasheader = False
If tbl.Rows.First.HeadingFormat = True Then
hasheader = True
End If
' get the column to do the sorting on. The column is identified by a comment with the "<RPE_SORT>" content in its first cell
Dim hcell As Cell
Dim index As Integer
pos = 0
For Each hcell In tbl.Rows.First.Cells
hcell.Select
If Selection.Comments.Count > 0 Then
If Selection.Comments.Item(1).Range.Text = "<RPE_SORT>" Then
pos = hcell.ColumnIndex
' Delete the comment - remove comment from the line below
' Selection.Comments.Item(1).Delete
Exit For
End If
End If
Next
' sorts the table using the found column
If pos > 0 Then
Dim fldnum As String
fldnum = "Column " + CStr(pos)
Debug.Print "Sorting on: "; fldnum
tbl.Select
Selection.Sort ExcludeHeader:=hasheader, FieldNumber:=fldnum, SortFieldType:=wdSortFieldAlphanumeric, SortOrder:=wdSortOrderAscending
End If
Next
End Sub
- Save the file with a .dot extension.
- Add the macro to the document specification and generate
the output:
- Open the document specification, if you already have
one, or create one in the Launcher application.
- Expand Output, right-click the Target:
Word, and select Configure Output.
- For the Stylesheet, click Browse to
locate the .dot macro you created.
- For the Macro, enter the name
of the macro.
- Generate the output.
What to do next
Save the macro and reuse it in any document specification
for sorting data.