Format Text in Word Using Excel VBA: A Full Guide

Visual Basic for Applications (VBA) provides a powerful set of tools for enhancing and automating tasks in Microsoft Word. This includes the ability to format text with precision. Through the use of VBA, users can efficiently manipulate various elements in the font group of the home tab, streamlining the document formatting experience.

In addition, VBA enables access to a broader range of formatting features that go beyond the basic font adjustments. By engaging with the dialogue launcher button, users can explore advanced formatting options, neatly facilitating the customization of their Word documents to meet specific requirements.

1. Adjusting Text Appearance

To modify text style within range or selection areas, one utilizes .Font properties. Assigning a specific typeface or altering text size can be achieved through:

  • Font Style: Set by assigning a typeface to .Font.name. For example:
    • .Font.name = "Arial"
  • Text Dimension: Adjusted by defining a numerical value to .Font.size. For instance:
    • .Font.size = 14

In Visual Basic for Applications (VBA), to dynamically resize text, one may employ methods analogous to manual font adjustment commands:

  • Enlarge Text: Activated by .Font.Grow, incrementally scaling font size up by available preset intervals.
  • Reduce Text: Triggered by .Font.Shrink, which sequentially decreases font size down by available presets.

Sequential method invocations result in incremental steps:

.Font.Grow ' Text size advances to the next interval
.Font.Shrink ' Text size retreats to the preceding interval

Utilizing these methods, users have the flexibility to fine-tune text presentation programmatically within their VBA projects.

Font Case

In programming Word’s font styles, the text case is controlled through a specific attribute within the range object framework. It is critically important to distinguish that this attribute is not part of the font object itself. Adjusting the text case involves selecting from predefined case styles, similar to those found in Word’s user interface.

To manipulate the text case in VBA, constants from an enumerated type are used. These constants correlate with the options available in the Word interface as follows:

  • Sentence case: When each sentence begins with a capital letter, with all subsequent letters in lowercase.
  • Lowercase: All letters are in lowercase.
  • Uppercase: All letters are capitalized.
  • Capitalize Each Word: The first letter of every word is capitalized.
  • Toggle case: Each letter’s case is switched from its current state (uppercase to lowercase and vice versa).

The choice between these options is made by setting the .Case property on the .Range object. The property accepts either the name of the constant or its corresponding index value. Here is how each case option appears within your code script:

  • Sentence case: .Range.Case = wdTitleSentence or .Range.Case = 4
  • Lowercase: .Range.Case = wdLowerCase or .Range.Case = 0
  • Uppercase: .Range.Case = wdUpperCase or .Range.Case = 1
  • Capitalize Each Word: .Range.Case = wdTitleWord or .Range.Case = 2
  • Toggle case: .Range.Case = wdToggleCase or .Range.Case = 5

For instance, to convert text to uppercase and then to lowercase, one would use the following lines of code:

.Range.Case = wdUpperCase
.Range.Case = wdLowerCase

3. Fundamental Text Effects

When editing text, you can adjust its appearance by changing properties or invoking methods that alter its style. These changes can be applied manually to selected text, or set to automatically affect new text as it’s typed.

For manual application, changing text properties is as simple as setting the corresponding attribute to “TRUE” or “FALSE”. Here are some basic commands affecting text style:

  • Bold Text: To bold a selection, activate .Font.Bold = True. To undo, use .Font.Bold = False.
  • Italic Text: Apply italics with .Font.Italic = True, revert with .Font.Italic = False.
  • Strikethrough: Strike a line through text using .Font.Strikethrough = True and remove with .Font.Strikethrough = False.
  • Subscript: To subscript, set .Font.Subscript = True or turn off with .Font.Subscript = False.
  • Superscript: For superscript, .Font.Superscript = True activates it; .Font.Superscript = False deactivates.

To toggle these effects while typing, use the methods on the .Selection object like .Selection.BoldRun for bold and .Selection.ItalicRun for italics.

Underline styling provides multiple patterns beyond simple on and off toggling. To define the style of underlining, you must specify an option, which are organized as named constants in an enumeration for ease of reference. See the table below for underline styles:

Underline Style Enumeration Name Enumeration Value
No Underlining wdUnderlineNone 0
Single Line wdUnderlineSingle 1
Word Only wdUnderlineWords 2
Double Line wdUnderlineDouble 3
Thick Line wdUnderlineThick 6
Dotted Line wdUnderlineDotted 4
Heavy Dotted wdUnderlineDottedHeavy 20
Dashed Line wdUnderlineDash 7
Heavy Dashed wdUnderlineDashHeavy 23
Long Dashed wdUnderlineDashLong 39
Heavy Long Dashed wdUnderlineDashLongHeavy 55
Dot Dash Pattern wdUnderlineDotDash 9
Heavy Dot Dash wdUnderlineDotDashHeavy 25
Double Dot Dash Pattern wdUnderlineDotDotDash 10
Heavy Double Dot Dash wdUnderlineDotDotDashHeavy 26
Wavy Line wdUnderlineWavy 11
Heavy Wavy Line wdUnderlineWavyHeavy 27
Double Wavy Line wdUnderlineWavyDouble 43

You can set the underline style by assigning either the enumeration name or value to .Font.Underline within the .Selection object as shown in the following examples:

  • Single Underline: .Font.Underline = wdUnderlineSingle
  • Double Underline: .Font.Underline = 3
  • Thick Underline: .Font.Underline = wdUnderlineThick
  • Dot Dash Underline: .Font.Underline = 9

These adjustments are essential for emphasizing text or conveying specific manuscript formatting requirements.

Text Effects and Type Enhancements

Effects on Text: Bordering

Text can be bordered using an automatic basic black border with a thickness of ¾ point. The command to enable this is .Font.Outline = True. For a custom border, one can adjust characteristics such as color, pattern, and thickness. For example, changing the border to a dotted dark red with a 1-point thickness involves setting .Font.Line.Visible = True followed by .Font.Line.ForeColor, .Font.Line.Weight, and .Font.Line.DashStyle to the desired values.

Effects on Text: Cast Shadow

Two approaches exist for adding a shadow to text: the automatic method produces a standard black shadow, while the custom method allows for adjustments in color, blur, and position. The code snippet .Font.Shadow = True activates the default shadow. For a custom shadow with specific attributes like light green color, 50% transparency, and a 2-point blur, settings within the .Font.TextShadow object are manipulated, making sure .TextShadow.Visible is set to True.

Effects on Text: Mirror Image

Reflections add a mirror-like effect and can be chosen from preset options or custom tailored. The code to select a preset reflection is .Font.Reflection.Type = msoReflectionType4, with the number indicating the chosen preset. Customizing the reflection includes adjusting the transparency, size, blur, and offset. The custom reflection should be reset to prevent it from affecting subsequent text by setting .Font.Reflection.Type = msoReflectionTypeNone.

Effects on Text: Luminosity

Glow effects, controlling brightness around text, have three modifiable aspects: color, radius, and transparency. To define a blue glow with a 2-point radius and 50% transparency, the corresponding properties inside .Font.Glow are set accordingly. To revert to normal, one must individually reset each property by altering .Font.Glow.Color, .Font.Glow.Radius, and .Font.Glow.Transparency as needed.

Art of Typesetting: Numeric Styling

The appearance of numbers in text can vary based on spacing — proportional or equal-width — and form — uniform height or varied baseline. The spacing affects the horizontal alignment while the form influences the vertical positioning. Commands to change these properties include .Font.NumberSpacing and .Font.NumberForm, with options for proportional, tabular, lining, or old-style numbers.

Art of Typesetting: Letter Pairing

Ligatures enhance text readability by linking specific letter combinations. Although often unused, their application can be managed through VBA, with ligatures types like contextual, discretional, historical, and standard available for inclusion. The .Font.Ligatures property can incorporate these, allowing for the selection of various combinations.

Art of Typesetting: Style Collections

Certain fonts offer multiple stylistic choices grouped into collections. To switch between available style sets, instructions such as .Font.StylisticSet = wdStylisticSet01 can be employed, with the numeral adjusted to indicate the desired set.

Type Effects|Command|Description|
|—|—|—|
|Bordering|.Font.Outline = True|Applies a solid line; customize with .Font.Line.*|
|Cast Shadow|.Font.Shadow = True|Applies a shadow; customize with .Font.TextShadow.*|
|Mirror Image|.Font.Reflection.Type = msoReflectionType*|Applies reflection; customize with .Font.Reflection.*|
|Luminosity|.Font.Glow.*|Applies glow; customize color, radius, transparency|

Typography Options|Command|Description|
|—|—|—|
|Numeric Styling|.Font.NumberSpacing .Font.NumberForm|Adjusts numeric alignment and vertical positioning|
|Letter Pairing|.Font.Ligatures|Creates connections between certain letter pairs|
|Style Collections|.Font.StylisticSet|Switches between style sets in supported fonts|

5. Highlighting Text and Adjusting Font Tint in Word

In Word, users have the capability to alter the background color of text using a feature analogous to font case selection. The selection choice presents an array of colors that are systematized in Visual Basic for Applications (VBA) as an enumerated list. Each color corresponds to both a descriptive name and a numerical index which are used when assigning a highlight to text via the .Range object’s property.

A summary of these options is outlined in the table below:

Menu Option Enumeration Identifier Numerical Reference
Default wdAuto 0
None wdNoHighlight 0
Obsidian wdBlack 1
Sapphire wdBlue 2
Sea Foam wdTurquoise 3
Lime wdBrightGreen 4
Flamingo wdPink 5
Crimson wdRed 6
Sunflower wdYellow 7
Snow wdWhite 8
Navy wdDarkBlue 9
Emerald wdTeal 10
Fern wdGreen 11
Lavender wdViolet 12
Maroon wdDarkRed 13
Mustard wdDarkYellow 14
Medium Gray wdGray50 15
Light Gray wdGray25 16

To assign a highlight, one must use the .HighlightColorIndex like so:

.Range.HighlightColorIndex = wdBlue  ' Sets highlight to blue
.Range.HighlightColorIndex = 3       ' Changes highlight to turquoise

Modifying font color within a document is achievable through the .Font object, utilizing either the predefined array of colors (ColorIndex) or specifying a custom color via the TextColor attribute, which accepts RED-Green-Blue (RGB) values, offering access to a spectrum of over 16 million hues.

For instance, changing the font color to blue and then to a custom blue-green shade would involve:

.Font.ColorIndex = wdBlue                       ' Sets font color to blue
.Font.TextColor = RGB(64,192,88)               ' Modifies font color to a specified blue-green

Choices for the font color are plentiful, despite this document not listing all, they are readily accessible within Word or by utilizing development tools such as intellisense or the object browser for a comprehensive view.

6. Enhanced Typography Features

Enhanced Feature: Dual Line Cancellation

Dual line cancellation, an enhanced typographical feature, allows for the application of two parallel lines through text to represent an additional layer of strikethrough beyond the standard single line. Implementing or removing this effect is straightforward, requiring a simple modification to the font property:

  • To apply dual line cancellation:
    • .Font.DoubleStrikeThrough = True
  • To remove dual line cancellation:
    • .Font.DoubleStrikeThrough = False

This command toggles the effect on and off, offering clear visual indication of revisions or updates in text documents.

7. Remove All Text Styles

To return a document’s text to its default style, apply the .Font.Reset function. This action strips away all existing text styles.

author avatar
Dean Portfolio Manager
Dean Graham is the founder and editor of 9to5flow.com, a website focused on productivity and work-life balance. Dean's career is in commercial banking where he has held various roles where he has encountered the everyday challenges faced by professionals. In 2022, Dean created 9to5flow.com to share practical advice and resources aimed at helping people achieve their goals while maintaining well-being. He hopes the site can provide readers with relatable insights and straightforward tips, as researching these topics has been a valuable exercise for his own career. Outside of the digital space, Dean enjoys the outdoors, college football, live music and being with his family. He finds happiness in continuous learning and helping others find a balanced approach to work and life.