Applying formatting to text

This topic includes Visual Basic examples related to the following tasks:

Applying formatting to the selection

The following example uses the Selection property to apply character and paragraph formatting to the selected text. Use the Font property to access character formatting properties and methods and the ParagraphFormat property to access paragraph formatting properties and methods.

With Selection.Font
    .Name = "Times New Roman"
    .Size = 14
    .AllCaps = True
End With
With Selection.ParagraphFormat
    .LeftIndent = InchesToPoints(0.5)
    .Space1
End With

Applying formatting to a range

The following example defines a Range object that refers to the first three paragraphs in the active document. The Range (myRange) is formatted by applying properties of the Font and ParagraphFormat objects.

Set myRange = ActiveDocument.Range( _
    Start:=ActiveDocument.Paragraphs(1).Range.Start, _
    End:=ActiveDocument.Paragraphs(3).Range.End)
With myRange
    .Font.Name = "Arial"
    .ParagraphFormat.Alignment = wdAlignParagraphJustify
End With

Inserting text and applying character and paragraph formatting

The following example adds the word Title at the top of the current document. The first paragraph is center aligned and a half inch space is added after the paragraph. The word Title is formatted with 24 point Arial font.

Set oRange = ActiveDocument.Range(Start:=0, End:=0)
With oRange
    .InsertAfter Text:="Title"
    .InsertParagraphAfter
    .Font.Name = "Arial"
    .Font.Size = 24
End With
With ActiveDocument.Paragraphs(1)
    .Alignment = wdAlignParagraphCenter
    .SpaceAfter = InchesToPoints(.5)
End With

Toggling the space before a paragraph between 12 points none

The following example toggles the space before formatting of the first paragraph in the selection. The macro retrieves the current space before value, and if the value is 12 points the space before formatting is removed (the SpaceBefore property is set to zero). If the space before value is anything other than 12, then SpaceBefore property is set to 12 points.

Set oParagraph = Selection.Paragraphs(1)
If oParagraph.SpaceBefore = 12 Then
    oParagraph.SpaceBefore = 0
Else
    oParagraph.SpaceBefore = 12
End If

Toggling bold formatting

The following example toggles bold formatting of the selected text.

Selection.Font.Bold = wdToggle

Increasing the left margin by 0.5 inch

The following example increases the left margin by 0.5 inch. The PageSetup object contains all the page setup attributes of a document (left margin, bottom margin, paper size, and so on) as properties. The LeftMargin property is used to return and set the left margin setting.

iMargin = ActiveDocument.PageSetup.LeftMargin
iMargin = iMargin + InchesToPoints(0.5)
ActiveDocument.PageSetup.LeftMargin = iMargin