Applying Formatting to Text
This topic includes Visual Basic examples related to the following tasks:
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.
Sub FormatSelection() With Selection.Font .Name = "Times New Roman" .Size = 14 .AllCaps = True End With With Selection.ParagraphFormat .LeftIndent = InchesToPoints(0.5) .Space1 End With End Sub
The following example defines a Range object that refers to the first three paragraphs in the active document. The Range is formatted by applying properties of the Font object and the ParagraphFormat object.
Sub FormatRange() Dim rngFormat As Range Set rngFormat = ActiveDocument.Range( _ Start:=ActiveDocument.Paragraphs(1).Range.Start, _ End:=ActiveDocument.Paragraphs(3).Range.End) With rngFormat .Font.Name = "Arial" .ParagraphFormat.Alignment = wdAlignParagraphJustify End With End Sub
The following example adds the word "Title" at the top of the current document. The first paragraph is center-aligned and one half-inch space is added after the paragraph. The word "Title" is formatted with 24-point Arial font.
Sub InsertFormatText() Dim rngFormat As Range Set rngFormat = ActiveDocument.Range(Start:=0, End:=0) With rngFormat .InsertAfter Text:="Title" .InsertParagraphAfter With .Font .Name = "Tahoma" .Size = 24 .Bold = True End With End With With ActiveDocument.Paragraphs(1) .Alignment = wdAlignParagraphCenter .SpaceAfter = InchesToPoints(0.5) End With End Sub
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, the SpaceBefore property is set to 12 points.
Sub ToggleParagraphSpace() With Selection.Paragraphs(1) If .SpaceBefore <> 0 Then .SpaceBefore = 0 Else .SpaceBefore = 6 End If End With End Sub
The following example toggles bold formatting of the selected text.
Sub ToggleBold() Selection.Font.Bold = wdToggle End Sub
The following example increases the left and right margins by 0.5 inch. The PageSetup object contains all the page setup attributes of a document (such as left margin, bottom margin, and paper size) as properties. The LeftMargin property is used to return and set the left margin setting. The RightMargin property is used to return and set the right margin setting.
Sub FormatMargins() With ActiveDocument.PageSetup .LeftMargin = .LeftMargin + InchesToPoints(0.5) .RightMargin = .RightMargin + InchesToPoints(0.5) End With End Sub