LoginSignup
7
6

More than 3 years have passed since last update.

[Word VBA]ソースコードをフォーマットする

Last updated at Posted at 2014-05-04

わけあって、私の仕事では、Word文書やPowerPoint文書にソースコードを貼ることが多い。
苦痛。

と思ってたら、
Microsoft Wordでソースコードをきれいに書く
なんて記事が。

というわけで、Word VBAです。これを使えば、Eclipseからwordに貼り付けたコードをそのまま
行番号付きでフォーマットできます。Eclipseで見たままのコードが、Word上でもフォーマットされて表示できる。
表形式にフォーマットするので、そのままPowerPointにも貼り付けられます。
あー、楽になった。

Sub PPCode()

    ActiveDocument.Select

    Dim codelines As Paragraphs
    Set codelines = Selection.Paragraphs

    Selection.Copy

    Dim lines As Long
    lines = codelines.Count

    Dim lineNumber As Integer
    lineNumber = 1

    Dim myTable As Table
    Set myTable = ActiveDocument.Tables.Add(ActiveDocument.Range(0, 0), lines, 2, wdWord9TableBehavior)

    myTable.Columns(1).Width = 30
    myTable.Columns(1).Select
    Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
    Selection.Font.Color = wdColorAutomatic
    myTable.Columns(2).Width = 400

    Call SetTablelines(myTable)

    For lineNumber = 1 To lines
        myTable.Cell(lineNumber, 1).Range.Text = lineNumber
    Next lineNumber

    myTable.Columns(2).Select
    Selection.Paste

    For Each s In ActiveDocument.Sentences
        s.Select
        If Selection.Information(wdWithInTable) = False Then
            Selection.Delete
        End If
    Next s

End Sub

Private Sub SetTablelines(ByRef myTable As Table)
'
' Macro1 Macro
'
'
    With myTable
        With .Borders(wdBorderLeft)
            .LineStyle = wdLineStyleSingle
            .LineWidth = wdLineWidth050pt
            .Color = wdColorAutomatic
        End With
        With .Borders(wdBorderRight)
            .LineStyle = wdLineStyleSingle
            .LineWidth = wdLineWidth050pt
            .Color = wdColorAutomatic
        End With
        With .Borders(wdBorderTop)
            .LineStyle = wdLineStyleSingle
            .LineWidth = wdLineWidth050pt
            .Color = wdColorAutomatic
        End With
        With .Borders(wdBorderBottom)
            .LineStyle = wdLineStyleSingle
            .LineWidth = wdLineWidth050pt
            .Color = wdColorAutomatic
        End With
        .Borders(wdBorderHorizontal).LineStyle = wdLineStyleNone
        With .Borders(wdBorderVertical)
            .LineStyle = wdLineStyleSingle
            .LineWidth = wdLineWidth050pt
            .Color = wdColorAutomatic
        End With
        .Borders(wdBorderDiagonalDown).LineStyle = wdLineStyleNone
        .Borders(wdBorderDiagonalUp).LineStyle = wdLineStyleNone
        .Borders.Shadow = False
    End With
    With Options
        .DefaultBorderLineStyle = wdLineStyleSingle
        .DefaultBorderLineWidth = wdLineWidth050pt
        .DefaultBorderColor = wdColorAutomatic
    End With
End Sub
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6