Source Code Formatter

プログラミング教育をしていると、ソースコードをWord文書や
PowerPointスライドに貼り付ける作業をすることがある。
そんなときのWordVBAマクロ。

1. Wordの新規文書に、ソースコードを貼り付ける。
2. マクロを実行する。
3. 表形式にフォーマットされたソースコードができる。

Eclipse->Word->PowerPoint
と変換することで、Eclipseの見た目通りに、PowerPointスライドを
作れる。

Sub FormatCode()

    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)
    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