Word VBA/マクロ 備忘録

作業効率化のため作成したマクロをバックアップ代わりにアップしていきます。

【Word VBA/マクロ】使用スタイルのリスト表示

サンプルコードでできること

使用しているスタイルの一覧を取得して、メッセージボックスに表示します。

Sub getStyleList_Activedocument()
    Dim strList As String
    strList = getStyleList(ActiveDocument)
    MsgBox strList
End Sub
Private Function getStyleList(dc As Document) As String
'使用した段落スタイルの一覧を取得します。
    Dim para As Paragraph, styleList As String
    Dim stl As Variant
    Dim dic As Scripting.Dictionary
    Set dic = New Scripting.Dictionary

    For Each para In dc.Paragraphs
        If dic.Exists(para.Style.NameLocal) = False Then
            dic.Add para.Style.NameLocal, ""
        End If
    Next
    
    For Each stl In dic.Keys
        styleList = styleList & stl & vbCrLf
    Next
    getStyleList = styleList
End Function

コードの説明

Wordではスタイルウインドウに「使用中のスタイル」を表示できます。
そのリストを取得するコードでいいと思ったのですが、「見出し 1」など使用されていないスタイルも含まれるようです。

段落ごとにスタイル名を取得していく無難な方法にしました。
For Eachを用いたリスト化は簡単ですが、スタイル名が重複します。
そのためDictionaryオブジェクトでスタイル名が登録されていないかチェック(dic.Exists(para.Style.NameLocal)しています。