Applying Character and Paragraph Formats in Office 2010
Working Programmatically with Shapes in Office 2010: Learn how to format characters and paragraphs in Microsoft Word 2010.
Last modified: May 19, 2011
Applies to: Excel 2010 | Office 2010 | PowerPoint 2010 | Word 2010
Published: June 2011
Provided by: Frank Rice, Microsoft Corporation
Formatting helps to call attention to characters and paragraphs. In this topic, you programmatically demonstrate the Selection.ClearCharacter and Selection.ClearParagraph methods. To complete this task, you must do the following:
In this task, you add programming code that manipulates character and paragraph formatting.
To add code to the Visual Basic Editor
Press Alt+F11 to open the Visual Basic Editor.
In the Projects pane, click ThisDocument.
Paste or type the following Microsoft Visual Basic for Applications (VBA) code into the module window.
Sub SelectionClearFormattingDemo() ' Apply character and paragraph formats. ' Press F8 to step into this the first time. ' Press Shift+F8 to step over subsequent lines of code: ApplyFormattingAndSelect Sentences(3) ' Note that the sentence is now formatted. ' Remove the character direct formatting; Selection.ClearCharacterDirectFormatting ' Reapply the formatting: ApplyFormattingAndSelect Sentences(3) ' Remove the character style formatting: Selection.ClearCharacterStyle ' Reapply the formatting: ApplyFormattingAndSelect Sentences(3) ' Remove all character formatting (leaving paragraph formatting): Selection.ClearCharacterAllFormatting ' Reapply the formatting: ApplyFormattingAndSelect Sentences(3) ' Remove the paragraph direct formatting: Selection.ClearParagraphDirectFormatting ' Reapply the formatting: ApplyFormattingAndSelect Sentences(3) ' Remove the paragraph style formatting: Selection.ClearParagraphStyle ' Reapply the formatting: ApplyFormattingAndSelect Sentences(3) ' Remove all paragraph formatting (leaving character formatting): Selection.ClearParagraphAllFormatting End Sub Sub ApplyFormattingAndSelect(rng As Range) With rng ' Apply a paragraph and character style: .Style = "Quote" ' Apply a character style: .Style = "Subtle Reference" ' Apply direct formatting: .Font.Bold = True .Font.ColorIndex = wdBrightGreen .ParagraphFormat.LineSpacing = 20 .Select End With End Sub
In this task, you add text to a document and then step through the VBA code to see the effects on character and paragraph formatting.
To step the code
In the document, type the following command (without the quotes) to add one paragraph of five sentences.
Drag the Visual Basic Editor to the right side of the screen.
Next, drag the Word window to the left side of the screen and adjust both windows until you can see them clearly.
Next, place the cursor in SelectionClearFormattingDemo procedure, press F8 to get started debugging, and then press Shift+F8 to step through the code line-by-line (and bypass external procedures) and watch the code behavior.