VBA: How to Customize Font to Specific Text in Word


Short one today.

I’m getting ready to write a post on worms and realized it’d be really nice if Word could mimic the font formatting that happens in the Visual Basic editor. Color coding helps me see relationships a lot easier when I’m trying to get my head around another person’s script.

The thing is, I like it customizable. I want to make specific variables orange, I want flow statements to be red, and I want to be able to flip that around easily if I’m still confused. Which (as far as I know), you can’t do in the Visual Basic editor.

However, this is actually not a terribly complicated thing if you VBA it. Start off with ActiveDocument to get the document you’re working on. Add .Content to get your text. Then you pop on a .Find to get yourself a fun new object to work with that picks out specific words.

Let’s talk about font properties. Those are things like color, italics, boldness, size, and underlining. You can use dot notation with the properties listed at that link to specify how you want the replacement text to appear.

You will need to use some With… End’s though.

What’s a With… End Statement?

With… End statements keep the script looking sane. You don’t have to use them. But I guarantee you’ll save hundreds of dollars in counseling sessions for your anger issues if you just embrace them now. They allow you to refer to an object once and then adjust things about that object without having to call it again.

To replace text, you’ll use a nested with statement (a with…end statement within a with…end statement, like a matryoshka doll). The inner with statement contains the font options for the replacement text. In the example below, I want it bold and blue.

The outer with statement executes the find search for a specific word, in this case “if.”

I’m going to replace it with the same word. I just want to get myself some new formatting. Like so:

With ActiveDocument.Content.Find
With .Replacement
.Font.Bold = True
.Font.Color = wdColorBlue
End With

.Execute FindText:="if", ReplaceWith:="if", _
Format:=True, Replace:=wdReplaceAll
End With

The Result:


Keep in mind, this will find every instance of the word With and change it. The ReplaceWith is half blue now, so you may still need to go through and adjust anything that you didn’t mean to have formatted.

Still a nice trick if you want to color code a 200 line script in Word.




Tagged , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: