Word VBA/マクロ 備忘録

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

【Word VBA/マクロ】蛍光マーカー(ハイライト)のテキスト抽出

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

蛍光マーカーのテキストを抽出して、別文書に蛍光マーカーのページとテキストの一覧を作成します。

コードの説明

Range.Findを用いて蛍光マーカーを検索。
Do While~Loopで見つかったマーカーにテキストが含まれている限り、検索を繰り返します。

            mkrList = mkrList & rng.Information(wdActiveEndPageNumber) _
                & vbTab & rng.Text & vbCrLf

蛍光マーカーのあるページとテキストを変数(mkrList)に格納します。
新規文書にまとめてmkrListの中身を書き出します。

            .SetRange .End, .End

検索された蛍光マーカーの直後にRangeをSetするという意味。
その位置以降で次の検索を行います。

Sub GetMarkerList()
'蛍光マーカー(ハイライト)の一覧を別文書に作成します。
    Dim rng As Range, mkrList As String, dcNew As Document
    Set rng = ActiveDocument.Range(0, 0)
    With rng.Find
        .Highlight = True
    End With
    
    With rng
        Do While .Find.Execute = True And .Text <> ""
            mkrList = mkrList & rng.Information(wdActiveEndPageNumber) _
                & vbTab & rng.Text & vbCrLf
            .SetRange .End, .End
        Loop
    End With
    If mkrList = "" Then
        MsgBox "ハイライトはありません"
        Exit Sub
    End If
    Set dcNew = Documents.Add'新規文書

    '一覧を作成する文書のページ設定
    With dcNew.PageSetup
        .TopMargin = MillimetersToPoints(30)
        .BottomMargin = MillimetersToPoints(30)
        .LeftMargin = MillimetersToPoints(30)
        .RightMargin = MillimetersToPoints(30)
    End With
    dcNew.Range(0, 0).InsertBefore mkrList
    
    '選択したテキストを表に変換
    With Selection
        .WholeStory
        .ConvertToTable Separator:=wdSeparateByTabs, NumColumns:=2, _
            AutoFitBehavior:=wdAutoFitFixed
        .InsertRowsAbove 1
        .TypeText Text:="ページ"
        .MoveRight Unit:=wdCell
        .TypeText Text:="ハイライト"
        With .Tables(1)
            .Style = "表 (格子)"
            .ApplyStyleHeadingRows = True
            .PreferredWidthType = wdPreferredWidthPercent
            .PreferredWidth = 100
            .Columns(1).PreferredWidth = 10
            .Columns(2).PreferredWidth = 90
        End With
    End With
End Sub