Need macro to color C keywords in a Word Document

T

Tom

In Word 2002, would a macro be the best way to find all
instances of 'C' programming language keywords in a Word
document and change them to a certain color? The words
are if, else, unsigned, short, return, long, for, int,
void, etc. I would like all of them to be Blue. They are
always all lower case. (If the same words in the document
are in upper or mixed case, they should not be changed to
Blue.) Also would like to find all comments - that always
start with /* and always end with */ - and change them to
Green. I am trying to display source code (text files
converted to Word documents) with more or less automatic
color coding of the keywords and comments similar to how
Visual Studio displays them. Having to click a button to
color format the document would be fine. Thanks.
 
A

Andrew Savikas

Kind of in a hurry, but this worked on your message --
It's a few subroutines and a function; run
the "ColorizeCode" macro on your document to do it all.
You'll need to add the full list of keywords.

HTH

Sub ColorizeCode()
Call ColorKeyWords
Call ColorComments
End Sub
Sub ColorKeyWords()
Dim arrKeywords(1 To 5) As String
Dim i As Integer

arrKeywords(1) = "if"
arrKeywords(2) = "else"
arrKeywords(3) = "unsigned"
arrKeywords(4) = "short"
arrKeywords(5) = "return"
' Fill in the rest

For i = 1 To UBound(arrKeywords)
Call ColorKeyWord(arrKeywords(i), wdBlue)
Next i

End Sub
Sub ColorComments()
With Selection.Find
.ClearFormatting
.Text = "/\*[!*]@\*/"
.Replacement.Text = ""
.Replacement.Font.ColorIndex = wdGreen
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
Exit Sub
End Sub
Function ColorKeyWord( _
ByVal strTextToFind As String, _
ByVal lngReplacementColor As Long)

With Selection.Find
.ClearFormatting
.Text = strTextToFind
.Replacement.Text = ""
.Replacement.Font.ColorIndex = lngReplacementColor
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
Exit Function
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top