20
Bonus Chapter B VBA Programming in Word In This Chapter An overview of the Word object model Key Word objects: Documents, windows, selections, ranges, and the Find object Ranges versus selections — when to use which of them for working with text Crucial methods and properties for manipulating text in your code How to find and replace text in Word VBA I n the Office suite, Word’s object model offers the richest array of program- ming treasures. Understanding Word objects, such as Range and Find, can be a challenge, but getting the hang of them is crucial if you’re going to be constructing VBA routines of any power in Word. That’s where this chapter comes in. Word’s object model encompasses so many objects and collections that you’d need a sizable wall poster to portray the object hierarchy in graphical form. Obviously, I can only cover a fraction of the objects, properties, and methods you can tap for your own programs. This chapter turns the spotlight on the most important Word VBA techniques. You should turn to the Help files for details once you grasp these fundamentals. Understanding the Application Object As in all VBA applications, the root object in Word’s object model is Application. In other words, the Application object contains all other Word objects. Because the Application object is so central to VBA programming in Word, you don’t need to explicitly mention it when working with many important Word objects. However, you shouldn’t forget its role because you need it to work with properties and methods of the application itself, as well as including in some object references. For example, the following statement triggers the ListCommands method of the Application object: Application.ListCommands ListAllCommands:=True

word vba wiley.pdf

Embed Size (px)

DESCRIPTION

about vba and word

Citation preview

Page 1: word vba wiley.pdf

Bonus Chapter B

VBA Programming in WordIn This Chapter� An overview of the Word object model

� Key Word objects: Documents, windows, selections, ranges, and the Find object

� Ranges versus selections — when to use which of them for working with text

� Crucial methods and properties for manipulating text in your code

� How to find and replace text in Word VBA

In the Office suite, Word’s object model offers the richest array of program-ming treasures. Understanding Word objects, such as Range and Find, can

be a challenge, but getting the hang of them is crucial if you’re going to beconstructing VBA routines of any power in Word. That’s where this chaptercomes in.

Word’s object model encompasses so many objects and collections that you’dneed a sizable wall poster to portray the object hierarchy in graphical form.Obviously, I can only cover a fraction of the objects, properties, and methodsyou can tap for your own programs. This chapter turns the spotlight on themost important Word VBA techniques. You should turn to the Help files fordetails once you grasp these fundamentals.

Understanding the Application ObjectAs in all VBA applications, the root object in Word’s object model isApplication. In other words, the Application object contains all other Wordobjects. Because the Application object is so central to VBA programmingin Word, you don’t need to explicitly mention it when working with manyimportant Word objects. However, you shouldn’t forget its role because youneed it to work with properties and methods of the application itself, as wellas including in some object references. For example, the following statementtriggers the ListCommands method of the Application object:

Application.ListCommands ListAllCommands:=True

Page 2: word vba wiley.pdf

By the way, the ListCommands method creates a new document and places init a table containing the keyboard shortcuts and menu locations of all Wordcommands. When you supply True as the value of the ListAllCommandsargument, the new document contains both custom keyboard and menuassignments. Switch to False if you only want to see custom assignmentsin the table.

Accessing Word Documents in VBAIf the VBA procedure you’re writing acts directly on a document, you mustspecify that document object in your code. Often, you can do so implicitly,using the Selection object, which I cover later in this chapter. But in othersituations, you must identify the target document explicitly.

Working with the active documentThe typical VBA procedure in Word performs its magic on the document thatthe Word user is currently editing. Use the ActiveDocument object to specifythis active document. The following statement closes the active document, ofcourse:

ActiveDocument.Close

The point is, you don’t need to write any code to figure out which documentis the one being edited at the time the procedure runs — just use theActiveDocument object.

Specifying a particular documentIf you need to work with a particular document that isn’t necessarily active,you must specify it as a member of the Documents collection, which containsall the documents currently open in Word. As with a generic VBA collection,you can refer to an individual document in the collection by its title, which inthis case is its file name (use the file name only, not the complete path).Here’s an example:

Documents(“Toy Store Newsletter.doc”)

Because you may not know the file name of the target document in advance,and because the user can change the document’s file name, you may want tocreate a variable to hold the name. You can then use the variable to specifythe document object, as in Documents(strDocName).

CD-18 VBA For Dummies, 3rd Edition

Page 3: word vba wiley.pdf

You can also refer to a document by index number. The following objectreference specifies the third document in the Documents collection:

Documents(3)

As simple as this technique may be, it’s of limited value — typically, you don’tknow the index number of the document that you want to work with. One usefor it is to learn the name of an open document. The following statementplaces the second open document’s file name in a variable:

strDocName = Documents(2).Name

Creating, opening, activating, and closing documentsTo create a brand-new document, use the Add method of the Documentscollection. Used without arguments, the Add method starts a documentbased on the Normal template. To specify another template, add its full pathas the argument as in the following:

Documents.Add template:= _“C:\Windows\Application data\Microsoft Office\Hidden

templates”

To open an existing document, you need the Open method — again a methodof the Documents collection. Of course, you have to include the completepath of the document file, as in

Documents.Open FileName:= _“C:\Toys\Toys for infants.doc”

Activate a document that’s already open with the Activate method. Supposeyou want your VBA program to activate a specific document that may or maynot be open already when the program runs. Use code similar to the followingto activate the document if it’s already open, or to open it if not:

Sub DocActivateOrOpen()Dim docFileName As String, docPath as StringdocFileName = “Pull toys.doc”docPath = “C:\Toys\”For Each targetDoc In Documents

If targetDoc.Name = docFileName ThentargetDocIsOpen = True

End IfNext targetDoc

CD-19Bonus Chapter B: VBA Programming in Word

Page 4: word vba wiley.pdf

If targetDocIsOpen = True ThenDocuments(docFileName).Activate

ElseDocuments.Open FileName:=docPath & docFileName

End IfEnd Sub

Working with document sectionsBecause each Word document has one or more sections, you might expectWord VBA to provide a Sections collection and individual Section objectsto work with these elements. And so it does. One important use of Sectionobjects is to access their headers and footers (via the HeaderFooter object).You can add new sections to a document by using the Add method of theSections collection or the InsertBreak method of a range or selectionobject.

Opening Windows with VBAEach open document has at least one window, but a Word user can open asmany windows as desired for any given document. Each of these windows isan object in its own right. In the Word object model, the Application objecthas a Windows collection containing all the windows of all open documents.In addition, each Document object has its own separate Windows collectionthat contains only the windows for that document.

Two main reasons to work with Window objects in Word are to control theappearance of the window and to manipulate document content via theSelection object. The topic that I discuss in the next section is the Selectionobject; here, I focus on the technique for specifying a particular window andalso on introducing the properties you can use to alter window appearance.

Specifying windows in codeThe easiest window to work with in code is the one that’s currently beingedited when the procedure runs. Use the ActiveWindow object to specifythis window.

To designate a specific window in code, identify it as a member of one of theWindows collections. You don’t have to name the Application object whenyou work with the global Windows collection. When you access a specificdocument’s Windows collection, however, a reference to that document isrequired. You can identify the window by its name or index number in the

CD-20 VBA For Dummies, 3rd Edition

Page 5: word vba wiley.pdf

collection. A window’s name is the same as the name of the document itdisplays — except if more than one window is open for the same document,you add a colon and the window number after the document name.

The following are typical object references for Window objects:

Reference Comments

Windows(“Document4”) Valid if Document4 has onlyone open window

Windows(“Kites and skip Specifies the third window ropes.doc:3”) of the named document

Documents(“Window display. Specifies the second window doc”).Windows(2) of the named document’s

Windows collection

Working with window panesWhen you split a window vertically by using the Window➪ Split command,the top and bottom portions of the window are separate panes. A Wordwindow has at least one pane, but it can have more than just one. The areaswhere Word displays headers, footers, footnotes, endnotes, and commentsare also panes.

If you have to access the appearance settings or the selection in an individualpane, you must first identify the target Pane object in your code. Refer to itby index number in its window’s Panes collection. However, you can omitpane references when you want to work with the default pane, which is themain part of the window (or the top pane if the window is split).

Changing window appearanceWindow objects offer a host of properties representing the state of all the ele-ments you see on-screen that are pertinent to an individual window. Anumber of these properties act as toggles — their values can be either Trueor False. For example, to turn on the Document Map for the active window,enter this statement in your code:

ActiveWindow.DocumentMap = True

Use similar statements to turn on or off properties such asDisplayScreenTips or DisplayVerticalScrollBar. Remember that thekeyword Not reverses the current value of a Boolean variable or property.It’s the easiest way to toggle such properties, as shown here:

CD-21Bonus Chapter B: VBA Programming in Word

Page 6: word vba wiley.pdf

ActiveWindow.DisplayRulers = _Not ActiveWindow.DisplayRulers

The Left, Top, Height, and Width properties enable you to set the size andlocation of a non-maximized window.

Using the View objectThe subsidiary View object governs many aspects of the appearance of awindow or pane. A few of the View object’s many properties include:

Property of View Object What It Does

Type Corresponds to the selection at the top of the Viewmenu (Normal, Outline, Print Layout, and so on). Tochange the view type, use one the following prede-fined constants: wdMasterView, wdNormalView,wdOutlineView, wdPrintView, wdWebView,or wdPrintPreview. For example, thestatement ActiveWindow.View.Type =wdPrintPreview switches the ActiveWindowto the Print Preview view.

FullScreen Controls whether the window is displayed in standardor full-screen view.

TableGridlines Determines whether table gridlines are visible or not.

ShowAll, Show ShowAll determines whether all non-printingcharacters are visible — it corresponds to thesetting of the All check box on the View tab of theTools➪ Options dialog box. You can turn the display ofeach individual type of non-printing characters on oroff, as well as other items such as text highlightingand boundaries with various properties that start withShow, such as ShowBookmarks andShowHighlight.

Zooming in codeTo control the window’s magnification, you need to drill down still deeperinto the object hierarchy to the Zoom object, and then modify its Percentageproperty. Here’s an example:

ActiveWindow.View.Zoom.Percentage = 135

CD-22 VBA For Dummies, 3rd Edition

Page 7: word vba wiley.pdf

If you want to preset the zoom factor for a view type that isn’t currentlydisplayed, include the constant for its type as an argument to the Viewproperty, as in

ActiveWindow.View.Zoom.Percentage = 75

The next time the user switches to that view, the document appears at thespecified zoom percentage.

Alternatively, you can use the PageFit property of the Zoom object to duplicatethe Page Width and Full Page choices in the Zoom drop-down toolbar button.With either of these settings active, Word re-zooms the document whenever thewindow size changes, ensuring that the correct fit is maintained. This statementis equivalent to selecting Page Width in the Zoom button:

ActiveWindow.View.Zoom.PageFit = wdPageFitBestFit

The Full Page choice is only available in Print Layout view, but you canduplicate it with the following code:

Windows(“Document1”).View.Zoom.PageFit = _wdPageFitFullPage

To shut off automatic re-zoom, set the PageFit property to wdPageFitNone.

Working with the Selection ObjectIn Word VBA, the Selection object refers to whatever is currently selectedin a window pane. That’s right, the Selection object belongs to a windowpane, not a document. Because a document can have more than one openwindow, each window can have more than one pane, and each of thesecontains a selection. (Although a Selection object technically belongs to awindow pane, it’s okay to think of it as belonging to a window instead, unlessyou specifically want to work with the selection in a special pane, such as aheader or footer.)

Although you can manipulate selections in your code by using the Selectionobject, it’s often better to use a Range object instead. See the section “Workingwith Text in Word VBA” later in this chapter for a discussion of when to useeach of these objects.

The content of a selection can be a block of text, a table, a text box, agraphic, or anything else you can select with the mouse or keyboard. Keypoint: If nothing is selected, the Selection object represents the currentlocation of the insertion point.

CD-23Bonus Chapter B: VBA Programming in Word

Page 8: word vba wiley.pdf

Although every window pane contains a selection, you only need to referexplicitly to the target window if the selection you want isn’t in the main paneof the active window. To work with the selection in the main pane of whateverwindow is active when the procedure runs, just use the Selection object byitself. For example, you can use the following statement to replace the activewindow’s selection with the text in quotation marks:

Selection.Text = “My dog has fleas.”

If you want to refer to a selection in one of the inactive windows, you mustspecify that window in full. Here’s an example:

Documents(“Songs.doc”).Windows(2).Selection.Text = _“My bonnie lies over the ocean.”

Because the Selection object can refer to many different types of content,it’s always best to check to see what type of content is selected before youperform some action on it. Otherwise, you risk unexpected results or errors.Use the Selection object’s Type property to provide this information. Forexample, the following code tests the selection to be sure it’s a regular textselection of one or more consecutive characters before proceeding to cut theselection to the Clipboard:

With SelectionIf .Type = wdSelectionNormal Then

.CutEnd If

You can use the following selection constants in such tests:

Selection.Type Constant What’s Selected

wdNoSelection No selection at all

wdSelectionBlock A vertical block of text

wdSelectionColumn A table column

wdSelectionFrame A frame

wdSelectionInlineShape A graphic residing in text

wdSelectionIP Just an insertion point — nothing is actuallyselected

wdSelectionNormal A standard selection consisting of consecutivetext characters

wdSelectionRow A table row

wdSelectionShape A floating graphic, not in-line with text

CD-24 VBA For Dummies, 3rd Edition

Page 9: word vba wiley.pdf

Understanding Range ObjectsWhen you’re editing a document yourself, you must position the insertionpoint or make a selection before adding, deleting, or formatting the text. InVBA, however, Word’s Range objects free you from that necessity. A Rangeobject simply specifies a continuous block of text of one or more charactersanywhere in a document. Range objects are completely independent of theinsertion point or highlighted selection that the user sees in the documentwindow. After you’ve created a Range object, you can then manipulate thetext it encompasses with VBA equivalents for all of Word’s powerful editingcommands, just as you can with Selection objects.

You can specify Range objects in your code in the following two ways:

� By accessing predefined ranges via the Range property

� By defining ranges yourself by using a Document object’s Range method

Using the Range propertyAn open Word document already contains Range objects that correspond tomany document elements. Each paragraph defines a range, as does each table,individual table cell, comment, and footnote, to name just a few examples. Youcan think of these ranges as existing only in a sort of virtual reality until youaccess them using the Range property of the object in question. For example,to specify the Range object represented by the first paragraph in the activedocument, you would use the following object reference:

ActiveDocument.Paragraphs(1).Range

Because these predefined ranges already exist in Word’s mind, you can useobject references to them directly, without assigning them to object variables.This is the way to go if you need a given range for a single operation. Thefollowing statement copies the document’s second table to the Clipboardusing the Range object’s Copy method:

ActiveDocument.Tables(2).Range.Copy

When multiple consecutive statements use the same range, you can use aWith... block to speed up code entry and the program. Here, this techniqueis used with a range representing the document’s third section to sort theparagraphs in the range and then make the first sentence bold:

With ActiveDocument.Section(3).Range.Sort SortOrder:=wdSortOrderAscending.Sentences(1).Range.Bold = True

End With

CD-25Bonus Chapter B: VBA Programming in Word

Page 10: word vba wiley.pdf

The above example illustrates how a Range object typically contains otherobjects that encompass ranges. The statement on the third line accesses therange corresponding to the first sentence in the original range, and thenmakes that sentence bold. Note too that you can’t apply formatting directlyto objects, such as words, sentences, or paragraphs — you must use theirRange properties to do so.

If you plan to use the range in multiple statements that aren’t consecutive, goahead and assign the range to an object variable. Again, doing so makes yourcode easier to type and your procedure a bit faster.

Selection objects also have the Range property. That fact makes it easy to usethe properties and methods belonging to Range objects on existing selections.The following example assigns the selection’s range to a variable, moves theselection, and then converts the text of the original range to all lowercasecharacters:

Set deRange = Selection.RangeSelection.Move Unit:=wdParagraph, Count:=3deRange.Case = wdLowerCase

Defining your own ranges by usingthe Range methodWhen existing objects don’t contain the text you want to work with, createyour own Range object. You can define as many Range objects as you need inany open documents. The technique relies on the document’s Range method,which requires you to specify the new range’s starting and end points interms of character position in the document. Check out this example:

ActiveDocument.Range (Start:=10, End:=20)

The preceding expression is an object reference to a range beginning with the11th character and ending with the 20th character in the document. Thecharacter position values actually refer to the place just to the left of a givencharacter where the insertion point would go. A value of 0 corresponds tothe location immediately to the left of the first character in the document,and a value of 10 to the spot just past the 10th character and just left of the11th character. Word counts all characters in the document, including hiddenand non-printing characters, whether or not they’re currently visible.

To create a range that’s just a location and contains no text, set the Startand End properties to the same number. To include the entire document inthe Range object, use the document’s Range method with no arguments, oruse the document’s Content property.

CD-26 VBA For Dummies, 3rd Edition

Page 11: word vba wiley.pdf

It’s easy enough to create a Range object — as long as you know the values forthe starting and ending characters that you want to include in it. The trouble is,you rarely want to work with an arbitrary number of characters at an arbitrarylocation in your document. More often, you’re interested in text at meaningfulplaces in the document. You might want to begin a range at an existing book-mark, at the start of the current selection or an existing range, or at a particularword or phrase that you know is somewhere in the document.

To define a range based on some such item, use the Start or End propertiesof a Selection, Range, or Bookmark object to learn the character positionvalue that you need. If you want to create a 10-character range starting at abookmark named ForgetMeNot, these statements do the trick:

With ActiveDocumentSet myBkMark = .Bookmarks(“ForgetMeNot”)Set homeOnTheRange = _

.Range (Start:= myBkMark, End:= myBkMark + 10)End With

The following is another example showing how you can use the Range propertyto locate a paragraph, focus in on a particular word it contains, and then use thebeginning of the word as the start of a new range. Here, the End argument isomitted, so the range extends from that point to the end of the document:

With ActiveDocumentSet firstWord = .Paragraphs(160).Range.Words(3)Set RangeTop =.Range (Start:= firstWord.Start)

End With

As I discuss in the section “ Finding and Replacing in Word VBA,” later in thischapter, using Find with a range or selection redefines the object to encompassonly the text that it finds. So, after Find locates a phrase in a range or selection,the Start or End properties for the same range or selection now identify thestart and end positions of the found text.

Working with Text in Word VBARange and Selection objects are the starting points for almost everythingyou can do to text in Word VBA. Some text manipulations can be applied todocuments as a whole, but in general, you need a range or selection beforeyou can make changes.

Range and Selection objects have a great deal in common, but they also haveimportant differences. Both represent continuous sequences of characters,upon which you can perform all kinds of editing magic. They share the majorityof their properties and methods. However, some properties and methods areunique to selections and some to ranges. The big differences, of course, are that

CD-27Bonus Chapter B: VBA Programming in Word

Page 12: word vba wiley.pdf

a Selection object corresponds to a window pane’s one visible selection —which can be text, graphics, or other items — while Range objects existindependently of the selection, always consist of text, and can be accessed inany number.

Use the Selection object when your procedure depends on the user toidentify the text to be manipulated, or when you want to show the user thetext being changed. Range objects are better otherwise. They make yourprogram faster and less distracting to the user — Word updates the screenevery time the selection changes, but leaves the screen alone when modifyinga range. In addition, range modifications politely leave the user’s selectionundisturbed.

Selecting ranges, and creatingranges from selectionsDespite their differences, Selection and Range objects can be created easilyfrom one another. This capability is key. Many important editing functionswork only with ranges. Contrariwise, the only way to display the contents ofa range to the user is by selecting the range. Use these simple techniques:

� To select a range, use the range’s Select method. For a range objectcalled RangeR, the code is RangeR.Select.

� To access a range representing the same contents as a selection, use theselection’s Range property, as in Selection.Range.

Remember, if a text-related method calls for a range but you want to use it onthe selection, just include Selection.Range.MethodName in your code.

Redefining ranges and selectionsWord VBA offers a scad of methods for moving and resizing ranges andselections. I cover some of the most important of these in this section, butyou can find more by carefully studying the Help files.

Expanding a range or selectionThe Expand method makes an existing range or selection bigger by tacking aunit of text onto its end. The unit can be a character, word, or paragraph, or anyof a number of other predefined chunks. You can only add one of the specifiedunits at a time, however, and you can’t add units to the beginning of the rangeor selection. To add to the selection the word that immediately follows it, usethe following statement:

Selection.Expand(wdWord)

CD-28 VBA For Dummies, 3rd Edition

Page 13: word vba wiley.pdf

You can use any of the following constants to expand the object:wdCharacter, wdWord, wdSentence, wdParagraph, wdSection, wdStory,wdCell, wdColumn, wdRow, wdTable, and (for Selection objects only)wdLine. wdWord is the default.

Now for a potentially confusing point: Selection objects (but not ranges)also have an Extend method. This method turns on Word’s extend mode,which extends the selection when the user moves the insertion point. Eachtime that your program calls the Extend method, the selection grows by alarger unit of text to encompass — in sequence — the current word, sentence,paragraph, section, and document. If you specify a character argument, as inSelection.Extend(“C”), the selection extends to the next occurrence ofthat character instead.

Moving a range or selectionWord VBA permits you to redefine the beginning and end of a range or selectionat will. Just be aware that the methods that include “Move” in the name changethe location of the range or selection — they don’t actually move the textcontained in the object.

The Move method alters the range or selection by first collapsing it so that itmarks a location only and no longer contains any text. This location is thestarting position of the original object. The method then moves this collapsedobject according to your instructions. After the move is complete, you can usethe Expand or MoveEnd methods to make the object encompass text.

The following example moves the named range backward in the document bytwo paragraphs. Note that you use a named constant for the Unit argument (seethe section “Expanding a range or selection,” earlier in this chapter, for a list ofthese constants). The Count argument is a positive integer if you want to moveforward in the document (toward the end), negative to move backward. If therange or selection isn’t already collapsed, or if it falls inside a unit, the beginningor end of the current unit is counted as the first one of the move. In this example,no parentheses appear around the arguments because the method’s returnvalue — how many units were actually moved — isn’t used here.

onTheRange.Move Unit:=wdParagraph, Count:= -2

The MoveStart and MoveEnd methods work like Move, except that they onlychange the starting or ending position of the range or selection. The followingstatement moves the beginning of the selection three words closer to the endof the document:

Selection.MoveStart Unit:=wdWord, Count:=3

Note that if you move the object’s starting point past the end, Word collapsesthe range or selection and moves it as specified. The reverse occurs whenmoving the object’s end before the start.

CD-29Bonus Chapter B: VBA Programming in Word

Page 14: word vba wiley.pdf

Yet another pair of methods, StartOf and EndOf, move or extend the start orend position of a range or selection. StartOf moves the start of the objectbackward to the start of the current unit while EndOf moves the end of theobject forward to the end of the current unit.

You can use the Extend argument with either method to control whetherWord moves both the start and end simultaneously, collapsing the object oronly the side that’s being moved. If the side of the object being moved isalready at the side to which you’re moving, nothing happens. Use the wdMoveconstant to collapse the object or wdExtend to move only the specified side.Here’s an example:

Selection.StartOf Unit:=wdSentence, Extend:=wdMove

Collapsing a range or selectionOften, you must collapse a range or selection to a single position that doesn’tenclose any text. In technical terms, a collapsed range or selection is one inwhich the start and end are the same. Collapsing these objects is criticalwhen you want to insert a field, table, or other item before or after a selectionor range without replacing the object’s text. (You can insert plain text, newparagraphs, and some other items at a non-collapsed range or selection.)

Use the Collapse (what else?) method to collapse a range or selection. Youcan collapse the object to the original starting or ending position, as youprefer, by using the optional Direction argument. The following examplecollapses the selection to its start:

Selection.Collapse

This second example collapses a range object to its end:

Selection.Collapse(Direction:=wdCollapseEnd)

If you collapse a range that ends with a paragraph mark to its end (by usingwdCollapseEnd), Word places the collapsed range after the paragraph mark(that is, the collapsed range is located at the start of the next paragraph). Ifyou want to insert something in front of the original range’s paragraph mark,you must first move the range backward with the MoveEnd method via astatement such as this:

someRange.MoveEnd Unit:=wdCharacter, Count:=-1

Deleting, copying, and pasting textErasing all the text in a range or selection is easy — just use the object’sDelete method. You can use the Cut method instead if you want to remove thetext and place it on the Windows Clipboard. Of course, the Copy method putsthe text on the Clipboard without affecting the text in the range or selection.

CD-30 VBA For Dummies, 3rd Edition

Page 15: word vba wiley.pdf

You can insert text placed on the Clipboard into any range or selection withthat object’s Paste method. If the destination object isn’t already collapsed,the pasted text replaces the text in the object — just the way the Pastecommand works in Word.

Although using the Clipboard to transfer text from one location to another isa familiar method, it’s not the most efficient one. A better approach is to usethe Text or FormattedText properties of the destination range or selection.Set these properties equal to the range or selection containing the text thatyou want to transfer and you’re in business. The destination object shouldbe collapsed unless you want the transferred text to replace the object’sexisting text.

The following example transfers the text from the selection to a collapsedrange based on a bookmark (the fourth line actually performs the transfer).Only the text itself, without any formatting, gets copied to the new location.

With ActiveDocument.Bookmarks(“TheBookmark”)Set RangeY = _ActiveDocument.Range(Start:=.Start, End:=.Start)

End WithRangeY.Text = Selection.Text

To transfer all the formatting along with the text, just substitute theFormattedText property for the Text property on both sides of the equal sign.

Inserting new textThe easiest text-adding technique to remember is to set the Text property ofa range or selection to the text you want to insert. The following statementillustrates this:

Range2.Text = “Hey, ho, nobody home”

Just remember that setting the Text property replaces the existing text, ifany, in the range or selection. To avoid replacing existing text (unless that’syour intention), collapse the object first.

Use the InsertBefore or InsertAfter methods of a range or selectionobject to insert text at a specific location in a document without destroyingthe object’s existing text. These methods place the new text immediatelybefore the start or after the end of the object in question, respectively. Wordincludes the inserted text in the selection or range.

With either method, the only argument is the text you want to insert. Thefollowing example inserts a new paragraph containing the text “Diary entry”at the beginning of the selection (note the use of the VBA constant vbCr to

CD-31Bonus Chapter B: VBA Programming in Word

Page 16: word vba wiley.pdf

insert a paragraph mark). It then adds a paragraph stating today’s date at theend. If you select an entire paragraph before running this code, the dateparagraph appears after the paragraph mark in the selection.

Dim strInsertText As StringSelection.InsertBefore “Diary entry” & vbCrstrInsertText = “Today” & Chr(146) & “s date is “strInsertText = _

strInsertText & Format(Now, “Long date”) & “. “Selection.InsertAfter strInsertText & vbCr

The example shows how inserted text can include string variables and VBAfunctions that return strings, as well as literal text and VBA constants. SeeChapter 11 for information on formatting and modifying strings in VBA.

The easiest way to add a new, empty paragraph to a document is to insert aparagraph mark (represented by the constant vbCr) with the Text propertyor InsertBefore/InsertAfter methods. The Add method used on aParagraphs collection also works, but it’s more cumbersome. Use it only ifyou want to place the new paragraph within a range or selection rather thanat the beginning or end.

Formatting textSeveral key properties of a range or selection are your gateways to changingthe appearance of the text. These properties correspond to the items inWord’s Format menu, and they function as follows:

This Property Gives Access To

Font Subsidiary properties for each aspect of characterformatting, such as Name, Size, and Bold. For somereason, you can directly access the most commoncharacter formatting properties on Range objects, withoutgoing through the Font property, but not on selections.

ParagraphFormat Subsidiary properties for each aspect of paragraphformatting, such as LeftIndent and LineSpacing.

Style The name of the character or paragraph Style applied tothe range or selection.

Borders The borders around the text.

TabStops Types and locations of tab stops. You can access thisproperty only through Paragraph objects, not directlyvia ranges or selections.

CD-32 VBA For Dummies, 3rd Edition

Page 17: word vba wiley.pdf

Finding and Replacing in Word VBAAlthough it sounds like an imperative, Find is an object in Word VBA. Findobjects belong to ranges and selections. Locating text or formatting with aFind object requires the following steps:

1. Access the Find object for a particular range or selection. If you want tosearch the entire document, use the Document object’s Content propertyto access the corresponding range, as in the following:

ActiveDocument.Content.Find

2. Set the Find object’s properties corresponding to what you’re lookingfor and how you want to look for it.

3. Trigger the Find object’s Execute method. Here’s an example of thetechnique:

With OpenRange.Find.ClearFormatting.Text = “pogo sticks”.Execute

End With

For properties you don’t explicitly set, the Find object takes on the optionsthat were last used or that are currently set in Word’s Find and Replace dialogbox. That’s why you should always include the ClearFormatting methodwhen you’re starting a new search — it removes any formatting that mayhave been previously specified from the search request.

Working with found textThe Execute method’s job is to locate the first occurrence of the search textor formatting in the specified range or selection. After the Execute methodruns, your first programming concern is to see whether or not it found thetext you were looking for. Use the Find object’s Found property with anIf...Then statement to perform this test, as in this sample code skeleton:

If .Found = True Then(take action on the found text)

Else(display an appropriate message)

End If

If the Execute method finds the search text, the original range or selection isredefined so that it encompasses the found text. This is a key point, becauseit means that you can work directly with that text through the originalobject’s properties and methods. In the following code, an expansion of thefirst example in this section, the statement .Parent.Italic = True refers

CD-33Bonus Chapter B: VBA Programming in Word

Page 18: word vba wiley.pdf

to the parent of the Find object, that is, the range called OpenRange. If thatstatement runs, OpenRange now encompasses only the found text — so onlythat text will be formatted in italic.

With OpenRange.Find.ClearFormatting.Text = “pogo sticks”.ExecuteIf .Found = True Then

.Parent.Italic = TrueElse

MsgBox “No pogo sticks found.”End If

End With

Replacing text or formattingThe Replacement object belongs to (that is, it’s a property of) the Find object.To code a search and replace operation, you set properties and trigger methodsof the Replacement object.

The following example replaces all occurrences of the word “pogo sticks”with “skateboards.” The selection changes when the find criterion is foundbecause the Find object is accessed from the Selection object.

With ActiveDocument.Content.Find.ClearFormatting.Text = “pogo sticks”With .Replacement

.ClearFormatting

.Text = “skateboards” End With.Execute Replace:=wdReplaceAll

End With

Note that the Execute method can take a Replace argument, used to controlwhether all occurrences of the found text, or only the first, get replaced.

Finding and replacing formattingTo search for text that’s formatted a certain way, use the Find object’s format-related properties. These are identical to the properties you use to work withformatting of a range or selection, as I discuss in the section “Formatting text,”earlier in this chapter. You use these same properties on the Replacementobject if you want to specify formatting for the replacement text.

CD-34 VBA For Dummies, 3rd Edition

Page 19: word vba wiley.pdf

To search for any text with particular formatting, set the relevant Findproperties and then set the Text property to an empty string using a pair ofadjacent quotation marks. To change the formatting of found text withoutaltering the text itself, use an empty string for the Text property of theReplacement object. The following code searches for paragraphs currentlyassigned to the Drab style and applies the Frilly style to them instead:

With Selection.Find.ClearFormatting.Style = “Drab”.Text = “”With .Replacement

.ClearFormatting

.Style = “Frilly”

.Text = “”End With.Execute Replace:=wdReplaceAll.ClearFormatting.Replacement.ClearFormatting

End With

Including the two format-clearing statements in your procedures after theExecute method is a good idea. Otherwise, the next time the user opens theFind and Replace dialog box, she’ll have to clear formatting options manually.

Using Document VariablesUnique among the Office applications, Word allows you to define specialdocument variables in your code that it records with an individual documentfor later use. Document variables make it possible to store values used by aprocedure between editing sessions.

Create and access document variables as members of the document’sVariables collection. Like ordinary variables, document variables havenames. The following statement places the value of a document variablecalled Henry into an ordinary variable called FriendOfAnais.

FriendOfAnais = _ActiveDocument.Variables(“Henry”).Value

To create a new document variable, use the Variables collection’s Addmethod, as shown here:

Documents(“Document1”).Variables.Add _Name:=”TimesThisMacroHasRun”, Value:=0

CD-35Bonus Chapter B: VBA Programming in Word

Page 20: word vba wiley.pdf

Because you get an error if you try to add a document variable that alreadyexists, the safe way to create variables is by checking to see if the variablename already exists. If so, you can retrieve the value; if not, you can createthe variable and assign it an initial value. The following code illustrates thistechnique:

For Each DocVar In ActiveDocument.VariablesIf DocVar.Name = “LastCaption” _

Then DocIndex =DocVar.IndexNext DocVarIf DocIndex = 0 Then

ActiveDocument.Variables.Add _Name:=”LastCaption”, Value:=1

CaptionCounter = 1Else

CaptionCounter = _ActiveDocument.Variables(DocIndex).Value

End If

Even though the object models of the other Office applications don’t explicitlyprovide document variables, you can commandeer custom document propertiesfor the same purpose. See the “VBA Programming in Office” chapter on the CDfor information regarding the use of custom properties as document variables.

CD-36 VBA For Dummies, 3rd Edition