Microsoft Word 文書のマクロを使用したソート

使用したいプロパティーがソート・ウィンドウでは選択できない場合は、マクロを使用してソートします。

始める前に

注: このトピックは、Microsoft Word 文書に生成されるテンプレートに対してのみ適用されます。

このタスクについて

ソートにマクロを使用することの利点は、次のとおりです。

手順

  1. マクロ・ラベルをソート対象の列に次のように追加します。
    1. テンプレートを Document Studio アプリケーションで開きます。
    2. ソート基準とする列のヘッダー・セルに、「コメント」アイコン コメント・エレメントを追加します。
    3. コメントをダブルクリックして、<RPE_SORT> を入力します。
    4. 更新するテンプレート内の各テーブルにこれを繰り返します。
  2. マクロを作成します。
    1. Microsoft Word を開きます。
    2. 以下のスクリプトをコピーしてファイルに貼り付けます。
      ' 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
    3. ファイルを .dot 拡張子を付けて保存します。
  3. 以下のようにしてマクロを文書仕様に追加し、出力を生成します。
    1. 文書仕様を、既にそれがある場合には開き、ない場合にはランチャー・アプリケーションで作成します。
    2. 「出力」を展開し、「ターゲット: Word」を右クリックし、「出力の構成」を選択します。
    3. 「スタイル・シート」で、「参照」をクリックして、作成した .dot マクロを見つけます。
    4. 「マクロ」には、マクロの名前を入力します。
    5. 出力を生成します。

次のタスク

マクロを保存して、データをソートするために任意の文書仕様で再利用します。

フィードバック