Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse VBA macros to format text in Word to look like code
DescriptionThis example shows how to use VBA macros to format text in Word to look like code.
Keywordscode, format, Word, VBA
CategoriesOffice, Strings
 
To use these macros, define Code, Code First, Code Last, and Code Single styles. Typically these will all use a fixed-width font. You might add extra paragraph spacing before Code First, after Code Last, and both before and after Code Single. This separates the code from other text. You might also indent, use a slightly smaller font, and make the code bold. See the downloadable Word document for examples.

Subroutine ToCode calls subroutines SetCodeStyles, StraightenQuotes, and ColorComments to do the work.

 
' Format the selected text so it looks sort of like code.
' Note: First define the Code style.
Public Sub ToCode()
Dim selection_range As Range

    ' Get the selected range.
    Set selection_range = Selection.Range

    ' Set the code styles, straighten quotes, and color
    ' comments.
    SetCodeStyles selection_range
    StraightenQuotes selection_range
    ColorComments selection_range
End Sub
 
Subroutine SetCodeStyles sets the selected text's style. If the selection includes a single paragraph, it sets the paragraph's style to Code Single.

If the selection contains more than one paragraph, the code sets it's style to Code. It then sets the first and last paragraphs to Code First and Code Last.

 
' Set the range's last paragraph's style to Code Last.
' Set the other paragraphs' styles to Code.
Public Sub SetCodeStyles(ByVal rng As Range)
    Set selection_range = Selection.Range
    If selection_range.Paragraphs.Count = 1 Then
        selection_range.Style = ActiveDocument.Styles("Code " & _
            "Single")
    Else
        selection_range.Style = _
            ActiveDocument.Styles("Code")
        selection_range.Paragraphs(1).Style = _
            ActiveDocument.Styles("Code First")
        selection_range.Paragraphs(selection_range.Paragraphs.Count).Style _
            = ActiveDocument.Styles("Code Last")
    End If
End Sub
 
Subroutine StraightenQuotes replaces curly quotes with straight quotes. Notice how it turns AutoFormatAsYouTypeReplaceQuotes off before starting to prevent Word from automatically replacing the straight quotes with curly quotes. Also notics how it restores the original value for this setting when it is done.
 
' Replace curly quotes with straight quotes.
Public Sub StraightenQuotes(ByVal rng As Range)
Dim old_replace_quotes As Boolean

    old_replace_quotes = _
        Options.AutoFormatAsYouTypeReplaceQuotes
    Options.AutoFormatAsYouTypeReplaceQuotes = False

    rng.Find.ClearFormatting
    rng.Find.Replacement.ClearFormatting
    With rng.Find
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False

        .Text = "'"
        .Replacement.Text = "'"
        .Execute Replace:=wdReplaceAll

        .Text = """"
        .Replacement.Text = """"
        .Execute Replace:=wdReplaceAll
    End With

    Options.AutoFormatAsYouTypeReplaceQuotes = _
        old_replace_quotes
End Sub
 
Finally subroutine ColorComments makes comments green. It searches each paragraph character-by-character, keeping track of whether a quoted string is open. If it finds a single quote while a string is not open, it colors the rest of the paragraph green.
 
' Color comments green.
Public Sub ColorComments(ByVal rng As Range)
Dim para As Paragraph
Dim txt As String
Dim i As Integer
Dim ch As String
Dim quote_open As Boolean
Dim comment_range As Range

    ' Look for comments.
    For Each para In rng.Paragraphs
        txt = para.Range.Text
        quote_open = False
        For i = 1 To Len(txt)
            ch = Mid$(txt, i, 1)
            If ch = """" Then
                ' Open or close the current quote.
                quote_open = Not quote_open
            ElseIf ch = "'" Then
                ' See if a quote is open.
                If Not quote_open Then
                    ' No quote is open. This is comment.
                    Set rng = para.Range
                    rng.Start = rng.Start + i - 1
                    rng.Font.Color = wdColorGreen
                    Exit For
                End If
            End If
        Next i
    Next para
End Sub
 
For more information on programming the Microsoft Office applications with VBA code, see my book Microsoft Office Programming: A Guide for Experienced Developers.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated