Description

Bonus Chapter BVBA 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 n the Office suite, Word’s object model offers the richest array of programming 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. I 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 CD-18 VBA For Dummies, 3rd Edition By the way, the ListCommands method creates a new document and places in it a table containing the keyboard shortcuts and menu locations of all Word commands. When you supply True as the value of the ListAllCommands argument, the new document contains both custom keyboard and menu assignments. Switch to False if you only want to see custom assignments in the table. Accessing Word Documents in VBA If the VBA procedure you’re writing acts directly on a document, you must specify 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 other situations, you must identify the target document explicitly. Working with the active document The typical VBA procedure in Word performs its magic on the document that the Word user is currently editing. Use the ActiveDocument object to specify this active document. The following statement closes the active document, of course: ActiveDocument.Close The point is, you don’t need to write any code to figure out which document is the one being edited at the time the procedure runs — just use the ActiveDocument object. Specifying a particular document If 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 contains all 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 in this 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 to create a variable to hold the name. You can then use the variable to specify the document object, as in Documents(strDocName). as in Documents. One use for it is to learn the name of an open document. The following statement places the second open document’s file name in a variable: strDocName = Documents(2). it’s of limited value — typically. or to open it if not: Sub DocActivateOrOpen() Dim docFileName As String. docPath as String docFileName = “Pull toys. and closing documents To create a brand-new document.Name Creating.Bonus Chapter B: VBA Programming in Word You can also refer to a document by index number. add its full path as the argument as in the following: Documents. The following object reference specifies the third document in the Documents collection: Documents(3) CD-19 As simple as this technique may be. Suppose you want your VBA program to activate a specific document that may or may not be open already when the program runs.doc” docPath = “C:\Toys\” For Each targetDoc In Documents If targetDoc. opening. you don’t know the index number of the document that you want to work with. use the Add method of the Documents collection. the Add method starts a document based on the Normal template. To specify another template. you need the Open method — again a method of the Documents collection. you have to include the complete path of the document file. Use code similar to the following to activate the document if it’s already open. Of course.Open FileName:= _ “C:\Toys\Toys for infants.doc” Activate a document that’s already open with the Activate method.Name = docFileName Then targetDocIsOpen = True End If Next targetDoc . activating.Add template:= _ “C:\Windows\Application data\Microsoft Office\Hidden templates” To open an existing document. Used without arguments. but a Word user can open as many windows as desired for any given document. however. In the Word object model.CD-20 VBA For Dummies. The topic that I discuss in the next section is the Selection object. Two main reasons to work with Window objects in Word are to control the appearance of the window and to manipulate document content via the Selection object. One important use of Section objects is to access their headers and footers (via the HeaderFooter object). 3rd Edition If targetDocIsOpen = True Then Documents(docFileName).Open FileName:=docPath & docFileName End If End Sub Working with document sections Because each Word document has one or more sections. You can add new sections to a document by using the Add method of the Sections collection or the InsertBreak method of a range or selection object. In addition. you might expect Word VBA to provide a Sections collection and individual Section objects to work with these elements. a reference to that document is required. Specifying windows in code The easiest window to work with in code is the one that’s currently being edited when the procedure runs. identify it as a member of one of the Windows collections. And so it does. Use the ActiveWindow object to specify this window. You don’t have to name the Application object when you work with the global Windows collection. the Application object has a Windows collection containing all the windows of all open documents. I focus on the technique for specifying a particular window and also on introducing the properties you can use to alter window appearance. Each of these windows is an object in its own right. Opening Windows with VBA Each open document has at least one window. here. To designate a specific window in code. You can identify the window by its name or index number in the .Activate Else Documents. each Document object has its own separate Windows collection that contains only the windows for that document. When you access a specific document’s Windows collection. and comments are also panes. you can omit pane references when you want to work with the default pane. However. It’s the easiest way to toggle such properties. The areas where Word displays headers.Bonus Chapter B: VBA Programming in Word collection. endnotes.doc:3”) Documents(“Window display. If you have to access the appearance settings or the selection in an individual pane. you add a colon and the window number after the document name. footnotes. A number of these properties act as toggles — their values can be either True or False. The following are typical object references for Window objects: CD-21 Reference Windows(“Document4”) Windows(“Kites and skip ropes. doc”). as shown here: . footers. For example. but it can have more than just one. to turn on the Document Map for the active window. enter this statement in your code: ActiveWindow. you must first identify the target Pane object in your code. Remember that the keyword Not reverses the current value of a Boolean variable or property.Windows(2) Comments Valid if Document4 has only one open window Specifies the third window of the named document Specifies the second window of the named document’s Windows collection Working with window panes When you split a window vertically by using the Window➪Split command. which is the main part of the window (or the top pane if the window is split). A window’s name is the same as the name of the document it displays — except if more than one window is open for the same document. the top and bottom portions of the window are separate panes.DocumentMap = True Use similar statements to turn on or off properties such as DisplayScreenTips or DisplayVerticalScrollBar. Refer to it by index number in its window’s Panes collection. A Word window has at least one pane. Changing window appearance Window objects offer a host of properties representing the state of all the elements you see on-screen that are pertinent to an individual window. wdOutlineView. Controls whether the window is displayed in standard or full-screen view. Show Zooming in code To control the window’s magnification.Zoom.View. Top. Here’s an example: ActiveWindow.CD-22 VBA For Dummies. Height. You can turn the display of each individual type of non-printing characters on or off.Percentage = 135 . 3rd Edition ActiveWindow. wdNormalView. To change the view type. ShowAll determines whether all non-printing characters are visible — it corresponds to the setting of the All check box on the View tab of the Tools➪Options dialog box. and so on). For example. the statement ActiveWindow.Type = wdPrintPreview switches the ActiveWindow to the Print Preview view.View. wdWebView. use one the following predefined constants: wdMasterView. Determines whether table gridlines are visible or not.DisplayRulers = _ Not ActiveWindow. Using the View object The subsidiary View object governs many aspects of the appearance of a window or pane. Print Layout.DisplayRulers The Left. Outline. FullScreen TableGridlines ShowAll. wdPrintView. and then modify its Percentage property. such as ShowBookmarks and ShowHighlight. A few of the View object’s many properties include: Property of View Object Type What It Does Corresponds to the selection at the top of the View menu (Normal. as well as other items such as text highlighting and boundaries with various properties that start with Show. or wdPrintPreview. you need to drill down still deeper into the object hierarchy to the Zoom object. and Width properties enable you to set the size and location of a non-maximized window. a table.View. Because a document can have more than one open window.PageFit = _ wdPageFitFullPage To shut off automatic re-zoom.View. but you can duplicate it with the following code: Windows(“Document1”). include the constant for its type as an argument to the View property. set the PageFit property to wdPageFitNone. a text box. the Selection object represents the current location of the insertion point. the document appears at the specified zoom percentage. it’s okay to think of it as belonging to a window instead. With either of these settings active. a graphic. such as a header or footer. the Selection object refers to whatever is currently selected in a window pane. ensuring that the correct fit is maintained. Key point: If nothing is selected.View.Zoom. or anything else you can select with the mouse or keyboard. Word re-zooms the document whenever the window size changes. Alternatively. and each of these contains a selection. it’s often better to use a Range object instead.Zoom. The content of a selection can be a block of text. See the section “Working with Text in Word VBA” later in this chapter for a discussion of when to use each of these objects. as in ActiveWindow. That’s right.) Although you can manipulate selections in your code by using the Selection object.Zoom. the Selection object belongs to a window pane. you can use the PageFit property of the Zoom object to duplicate the Page Width and Full Page choices in the Zoom drop-down toolbar button. unless you specifically want to work with the selection in a special pane.PageFit = wdPageFitBestFit The Full Page choice is only available in Print Layout view. This statement is equivalent to selecting Page Width in the Zoom button: ActiveWindow. .Percentage = 75 CD-23 The next time the user switches to that view. each window can have more than one pane. not a document. Working with the Selection Object In Word VBA. (Although a Selection object technically belongs to a window pane.Bonus Chapter B: VBA Programming in Word If you want to preset the zoom factor for a view type that isn’t currently displayed. Otherwise. the following code tests the selection to be sure it’s a regular text selection of one or more consecutive characters before proceeding to cut the selection to the Clipboard: With Selection If .” If you want to refer to a selection in one of the inactive windows. you only need to refer explicitly to the target window if the selection you want isn’t in the main pane of the active window. you can use the following statement to replace the active window’s selection with the text in quotation marks: Selection.doc”).Text = “My dog has fleas. Here’s an example: Documents(“Songs.Cut End If You can use the following selection constants in such tests: Selection.Windows(2). For example.” Because the Selection object can refer to many different types of content.Selection. Use the Selection object’s Type property to provide this information. For example.Text = _ “My bonnie lies over the ocean.Type = wdSelectionNormal Then . it’s always best to check to see what type of content is selected before you perform some action on it. To work with the selection in the main pane of whatever window is active when the procedure runs. just use the Selection object by itself.CD-24 VBA For Dummies. not in-line with text . you must specify that window in full. you risk unexpected results or errors. 3rd Edition Although every window pane contains a selection.Type Constant wdNoSelection wdSelectionBlock wdSelectionColumn wdSelectionFrame wdSelectionInlineShape wdSelectionIP wdSelectionNormal wdSelectionRow wdSelectionShape What’s Selected No selection at all A vertical block of text A table column A frame A graphic residing in text Just an insertion point — nothing is actually selected A standard selection consisting of consecutive text characters A table row A floating graphic. After you’ve created a Range object.Section(3). You can think of these ranges as existing only in a sort of virtual reality until you access them using the Range property of the object in question. 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 property An open Word document already contains Range objects that correspond to many document elements.Sort SortOrder:=wdSortOrderAscending . The following statement copies the document’s second table to the Clipboard using the Range object’s Copy method: ActiveDocument. or formatting the text. block to speed up code entry and the program. Word’s Range objects free you from that necessity. A Range object simply specifies a continuous block of text of one or more characters anywhere in a document. Here. you can then manipulate the text it encompasses with VBA equivalents for all of Word’s powerful editing commands..Range . to specify the Range object represented by the first paragraph in the active document.Range. individual table cell. just as you can with Selection objects.Copy When multiple consecutive statements use the same range. Range objects are completely independent of the insertion point or highlighted selection that the user sees in the document window.Bold = True End With .Range.. This is the way to go if you need a given range for a single operation. as does each table.Range Because these predefined ranges already exist in Word’s mind. without assigning them to object variables. you can use a With.Bonus Chapter B: VBA Programming in Word CD-25 Understanding Range Objects When you’re editing a document yourself. you can use object references to them directly. you must position the insertion point or make a selection before adding. to name just a few examples. and footnote. Each paragraph defines a range.Tables(2). For example.Sentences(1). comment. you would use the following object reference: ActiveDocument. In VBA. this technique is used with a range representing the document’s third section to sort the paragraphs in the range and then make the first sentence bold: With ActiveDocument.Paragraphs(1). deleting. however. or paragraphs — you must use their Range properties to do so. doing so makes your code easier to type and your procedure a bit faster. use the document’s Range method with no arguments. A value of 0 corresponds to the location immediately to the left of the first character in the document. Note too that you can’t apply formatting directly to objects. The statement on the third line accesses the range corresponding to the first sentence in the original range. and a value of 10 to the spot just past the 10th character and just left of the 11th character.Move Unit:=wdParagraph. moves the selection. 3rd Edition The above example illustrates how a Range object typically contains other objects that encompass ranges. That fact makes it easy to use the properties and methods belonging to Range objects on existing selections. Again. The following example assigns the selection’s range to a variable. or use the document’s Content property.Case = wdLowerCase Defining your own ranges by using the Range method When existing objects don’t contain the text you want to work with. The character position values actually refer to the place just to the left of a given character where the insertion point would go.Range Selection.Range (Start:=10. If you plan to use the range in multiple statements that aren’t consecutive. whether or not they’re currently visible. The technique relies on the document’s Range method. including hidden and non-printing characters. which requires you to specify the new range’s starting and end points in terms of character position in the document. To create a range that’s just a location and contains no text. such as words. End:=20) The preceding expression is an object reference to a range beginning with the 11th character and ending with the 20th character in the document. You can define as many Range objects as you need in any open documents. set the Start and End properties to the same number. and then makes that sentence bold. . and then converts the text of the original range to all lowercase characters: Set deRange = Selection.CD-26 VBA For Dummies. sentences. create your own Range object. go ahead and assign the range to an object variable. Check out this example: ActiveDocument. Selection objects also have the Range property. To include the entire document in the Range object. Count:=3 deRange. Word counts all characters in the document. and then use the beginning of the word as the start of a new range. You might want to begin a range at an existing bookmark. focus in on a particular word it contains. at the start of the current selection or an existing range. So. Here. the Start or End properties for the same range or selection now identify the start and end positions of the found text. of course. upon which you can perform all kinds of editing magic. Working with Text in Word VBA Range and Selection objects are the starting points for almost everything you can do to text in Word VBA. Both represent continuous sequences of characters. some properties and methods are unique to selections and some to ranges. If you want to create a 10-character range starting at a bookmark named ForgetMeNot. Range and Selection objects have a great deal in common. They share the majority of their properties and methods.Bonus Chapter B: VBA Programming in Word It’s easy enough to create a Range object — as long as you know the values for the starting and ending characters that you want to include in it. Some text manipulations can be applied to documents as a whole. However. but they also have important differences. the End argument is omitted. using Find with a range or selection redefines the object to encompass only the text that it finds. are that .Range. End:= myBkMark + 10) End With CD-27 The following is another example showing how you can use the Range property to locate a paragraph. but in general. The big differences.Words(3) Set RangeTop =.Range (Start:= firstWord. use the Start or End properties of a Selection. More often.Paragraphs(160). you need a range or selection before you can make changes. after Find locates a phrase in a range or selection. Range. you’re interested in text at meaningful places in the document. or at a particular word or phrase that you know is somewhere in the document. To define a range based on some such item. so the range extends from that point to the end of the document: With ActiveDocument Set firstWord = . you rarely want to work with an arbitrary number of characters at an arbitrary location in your document.Bookmarks(“ForgetMeNot”) Set homeOnTheRange = _ .Range (Start:= myBkMark. The trouble is.Start) End With As I discuss in the section “ Finding and Replacing in Word VBA.” later in this chapter. or Bookmark object to learn the character position value that you need. these statements do the trick: With ActiveDocument Set myBkMark = . just include Selection. Use the Selection object when your procedure depends on the user to identify the text to be manipulated. or other items — while Range objects exist independently of the selection. and can be accessed in any number. if a text-related method calls for a range but you want to use it on the selection. use the following statement: Selection. or paragraph.Range. You can only add one of the specified units at a time. They make your program faster and less distracting to the user — Word updates the screen every time the selection changes. ߜ To access a range representing the same contents as a selection. or any of a number of other predefined chunks. graphics. but you can find more by carefully studying the Help files. Range objects are better otherwise. the code is RangeR. word. The unit can be a character. the only way to display the contents of a range to the user is by selecting the range. or when you want to show the user the text being changed. range modifications politely leave the user’s selection undisturbed. To add to the selection the word that immediately follows it. Selection and Range objects can be created easily from one another. use the selection’s Range property.Range. Use these simple techniques: ߜ To select a range. but leaves the screen alone when modifying a range. I cover some of the most important of these in this section. 3rd Edition a Selection object corresponds to a window pane’s one visible selection — which can be text.Expand(wdWord) .Select. Remember.CD-28 VBA For Dummies. Contrariwise. For a range object called RangeR. Expanding a range or selection The Expand method makes an existing range or selection bigger by tacking a unit of text onto its end. In addition. Many important editing functions work only with ranges. Selecting ranges.MethodName in your code. Redefining ranges and selections Word VBA offers a scad of methods for moving and resizing ranges and selections. This capability is key. and creating ranges from selections Despite their differences. and you can’t add units to the beginning of the range or selection. use the range’s Select method. always consist of text. however. as in Selection. If you specify a character argument. The method then moves this collapsed object according to your instructions. or if it falls inside a unit. Note that you use a named constant for the Unit argument (see the section “Expanding a range or selection. This method turns on Word’s extend mode. wdWord is the default. The reverse occurs when moving the object’s end before the start. as in Selection. section.Extend(“C”). In this example. wdSection. no parentheses appear around the arguments because the method’s return value — how many units were actually moved — isn’t used here. wdWord. and (for Selection objects only) wdLine. except that they only change the starting or ending position of the range or selection. which extends the selection when the user moves the insertion point. you can use the Expand or MoveEnd methods to make the object encompass text. The Move method alters the range or selection by first collapsing it so that it marks a location only and no longer contains any text.Bonus Chapter B: VBA Programming in Word You can use any of the following constants to expand the object: wdCharacter. wdSentence. negative to move backward. This location is the starting position of the original object. wdRow. wdStory. Just be aware that the methods that include “Move” in the name change the location of the range or selection — they don’t actually move the text contained in the object. sentence. wdColumn. The following statement moves the beginning of the selection three words closer to the end of the document: Selection. and document. If the range or selection isn’t already collapsed. the selection grows by a larger unit of text to encompass — in sequence — the current word. Each time that your program calls the Extend method. Word collapses the range or selection and moves it as specified. Count:=3 Note that if you move the object’s starting point past the end. The following example moves the named range backward in the document by two paragraphs. paragraph. onTheRange.” earlier in this chapter. Count:= -2 The MoveStart and MoveEnd methods work like Move. the selection extends to the next occurrence of that character instead. After the move is complete. wdTable. CD-29 Moving a range or selection Word VBA permits you to redefine the beginning and end of a range or selection at will. Now for a potentially confusing point: Selection objects (but not ranges) also have an Extend method. for a list of these constants). wdParagraph.Move Unit:=wdParagraph. wdCell. The Count argument is a positive integer if you want to move forward in the document (toward the end). .MoveStart Unit:=wdWord. the beginning or end of the current unit is counted as the first one of the move. move or extend the start or end position of a range or selection. nothing happens.) Use the Collapse (what else?) method to collapse a range or selection.Collapse This second example collapses a range object to its end: Selection. .CD-30 VBA For Dummies. If you want to insert something in front of the original range’s paragraph mark. Of course. 3rd Edition Yet another pair of methods. Here’s an example: Selection. or other item before or after a selection or range without replacing the object’s text.Collapse(Direction:=wdCollapseEnd) If you collapse a range that ends with a paragraph mark to its end (by using wdCollapseEnd). Count:=-1 Deleting. collapsing the object or only the side that’s being moved. and some other items at a non-collapsed range or selection. by using the optional Direction argument. StartOf moves the start of the object backward to the start of the current unit while EndOf moves the end of the object forward to the end of the current unit. If the side of the object being moved is already at the side to which you’re moving. You can collapse the object to the original starting or ending position. Extend:=wdMove Collapsing a range or selection Often. you must first move the range backward with the MoveEnd method via a statement such as this: someRange. StartOf and EndOf. In technical terms. Collapsing these objects is critical when you want to insert a field. The following example collapses the selection to its start: Selection. and pasting text Erasing all the text in a range or selection is easy — just use the object’s Delete method. Word places the collapsed range after the paragraph mark (that is. you must collapse a range or selection to a single position that doesn’t enclose any text. the collapsed range is located at the start of the next paragraph). as you prefer. Use the wdMove constant to collapse the object or wdExtend to move only the specified side. new paragraphs. You can use the Cut method instead if you want to remove the text and place it on the Windows Clipboard. copying. the Copy method puts the text on the Clipboard without affecting the text in the range or selection. table. You can use the Extend argument with either method to control whether Word moves both the start and end simultaneously. (You can insert plain text.MoveEnd Unit:=wdCharacter. a collapsed range or selection is one in which the start and end are the same.StartOf Unit:=wdSentence. gets copied to the new location. just substitute the FormattedText property for the Text property on both sides of the equal sign. The following statement illustrates this: Range2. These methods place the new text immediately before the start or after the end of the object in question. Use the InsertBefore or InsertAfter methods of a range or selection object to insert text at a specific location in a document without destroying the object’s existing text. in the range or selection. the only argument is the text you want to insert. respectively.Text CD-31 To transfer all the formatting along with the text. With either method.Bookmarks(“TheBookmark”) Set RangeY = _ ActiveDocument. To avoid replacing existing text (unless that’s your intention). ho. without any formatting. The following example transfers the text from the selection to a collapsed range based on a bookmark (the fourth line actually performs the transfer). The following 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 .Text = Selection.Text = “Hey. the pasted text replaces the text in the object — just the way the Paste command works in Word. If the destination object isn’t already collapsed. Set these properties equal to the range or selection containing the text that you want to transfer and you’re in business. Only the text itself.Start. With ActiveDocument. The destination object should be collapsed unless you want the transferred text to replace the object’s existing text. Although using the Clipboard to transfer text from one location to another is a familiar method. End:=. it’s not the most efficient one.Bonus Chapter B: VBA Programming in Word You can insert text placed on the Clipboard into any range or selection with that object’s Paste method. Inserting new text The easiest text-adding technique to remember is to set the Text property of a range or selection to the text you want to insert. collapse the object first. A better approach is to use the Text or FormattedText properties of the destination range or selection.Range(Start:=.Start) End With RangeY. if any. nobody home” Just remember that setting the Text property replaces the existing text. Word includes the inserted text in the selection or range. but it’s more cumbersome.InsertAfter strInsertText & vbCr The example shows how inserted text can include string variables and VBA functions that return strings. Subsidiary properties for each aspect of paragraph formatting. The name of the character or paragraph Style applied to the range or selection. If you select an entire paragraph before running this code. the date paragraph appears after the paragraph mark in the selection. Use it only if you want to place the new paragraph within a range or selection rather than at the beginning or end.CD-32 VBA For Dummies. It then adds a paragraph stating today’s date at the end. The easiest way to add a new. “Long date”) & “. Types and locations of tab stops. not directly via ranges or selections. empty paragraph to a document is to insert a paragraph mark (represented by the constant vbCr) with the Text property or InsertBefore/InsertAfter methods. you can directly access the most common character formatting properties on Range objects. See Chapter 11 for information on formatting and modifying strings in VBA. such as Name. Formatting text Several key properties of a range or selection are your gateways to changing the appearance of the text. such as LeftIndent and LineSpacing. The borders around the text. and they function as follows: This Property Font Gives Access To Subsidiary properties for each aspect of character formatting. For some reason. without going through the Font property. You can access this property only through Paragraph objects. “ Selection. These properties correspond to the items in Word’s Format menu. Dim strInsertText As String Selection. 3rd Edition insert a paragraph mark). and Bold. as well as literal text and VBA constants.InsertBefore “Diary entry” & vbCr strInsertText = “Today” & Chr(146) & “s date is “ strInsertText = _ strInsertText & Format(Now. The Add method used on a Paragraphs collection also works. Size. but not on selections. ParagraphFormat Style Borders TabStops . Trigger the Find object’s Execute method. as in the following: ActiveDocument. the Find object takes on the options that were last used or that are currently set in Word’s Find and Replace dialog box. an expansion of the first example in this section.Bonus Chapter B: VBA Programming in Word CD-33 Finding and Replacing in Word VBA Although it sounds like an imperative. because it means that you can work directly with that text through the original object’s properties and methods.Find . the statement . That’s why you should always include the ClearFormatting method when you’re starting a new search — it removes any formatting that may have been previously specified from the search request. Use the Find object’s Found property with an If.Find 2.Found = True Then (take action on the found text) Else (display an appropriate message) End If If the Execute method finds the search text. Find objects belong to ranges and selections.Execute End With For properties you don’t explicitly set.Content. After the Execute method runs.. Here’s an example of the technique: With OpenRange. In the following code. If you want to search the entire document. as in this sample code skeleton: If .Text = “pogo sticks” . 3.Italic = True refers .ClearFormatting . Working with found text The Execute method’s job is to locate the first occurrence of the search text or formatting in the specified range or selection. This is a key point. Locating text or formatting with a Find object requires the following steps: 1. Find is an object in Word VBA. Access the Find object for a particular range or selection. Set the Find object’s properties corresponding to what you’re looking for and how you want to look for it.Then statement to perform this test. your first programming concern is to see whether or not it found the text you were looking for.Parent. use the Document object’s Content property to access the corresponding range. the original range or selection is redefined so that it encompasses the found text.. Replacement .Text = “pogo sticks” With . 3rd Edition to the parent of the Find object. Finding and replacing formatting To search for text that’s formatted a certain way.Find . .Text = “skateboards” End With .Italic = True Else MsgBox “No pogo sticks found.Found = True Then .Parent.” earlier in this chapter. get replaced. you set properties and trigger methods of the Replacement object. the range called OpenRange.Find .Content.” The selection changes when the find criterion is found because the Find object is accessed from the Selection object. The following example replaces all occurrences of the word “pogo sticks” with “skateboards.ClearFormatting . as I discuss in the section “Formatting text. or only the first. that is.Execute Replace:=wdReplaceAll End With Note that the Execute method can take a Replace argument.Text = “pogo sticks” . With OpenRange.ClearFormatting . OpenRange now encompasses only the found text — so only that text will be formatted in italic. used to control whether all occurrences of the found text.” End If End With Replacing text or formatting The Replacement object belongs to (that is. With ActiveDocument. If that statement runs.ClearFormatting .CD-34 VBA For Dummies. it’s a property of) the Find object. You use these same properties on the Replacement object if you want to specify formatting for the replacement text.Execute If . These are identical to the properties you use to work with formatting of a range or selection. To code a search and replace operation. use the Find object’s formatrelated properties. ClearFormatting . she’ll have to clear formatting options manually.Text = “” With .Text = “” End With .Value To create a new document variable. use the Variables collection’s Add method. document variables have names. Using Document Variables Unique among the Office applications.Variables.Style = “Frilly” . The following code searches for paragraphs currently assigned to the Drab style and applies the Frilly style to them instead: With Selection.ClearFormatting . Create and access document variables as members of the document’s Variables collection. Like ordinary variables. use an empty string for the Text property of the Replacement object.Execute Replace:=wdReplaceAll . FriendOfAnais = _ ActiveDocument. Document variables make it possible to store values used by a procedure between editing sessions.Replacement . Value:=0 .ClearFormatting .Find . Otherwise.Style = “Drab” . as shown here: Documents(“Document1”).ClearFormatting End With CD-35 Including the two format-clearing statements in your procedures after the Execute method is a good idea.Bonus Chapter B: VBA Programming in Word To search for any text with particular formatting.Variables(“Henry”). set the relevant Find properties and then set the Text property to an empty string using a pair of adjacent quotation marks. To change the formatting of found text without altering the text itself.Replacement. the next time the user opens the Find and Replace dialog box. The following statement places the value of a document variable called Henry into an ordinary variable called FriendOfAnais.Add _ Name:=”TimesThisMacroHasRun”. Word allows you to define special document variables in your code that it records with an individual document for later use. Variables.Index Next DocVar If DocIndex = 0 Then ActiveDocument.Variables(DocIndex).Value End If Even though the object models of the other Office applications don’t explicitly provide document variables. See the “VBA Programming in Office” chapter on the CD for information regarding the use of custom properties as document variables.Add _ Name:=”LastCaption”. you can retrieve the value.Variables If DocVar. if not. The following code illustrates this technique: For Each DocVar In ActiveDocument. the safe way to create variables is by checking to see if the variable name already exists. you can create the variable and assign it an initial value. . 3rd Edition Because you get an error if you try to add a document variable that already exists. Value:=1 CaptionCounter = 1 Else CaptionCounter = _ ActiveDocument.CD-36 VBA For Dummies. If so.Name = “LastCaption” _ Then DocIndex =DocVar. you can commandeer custom document properties for the same purpose.
Copyright © 2024 DOKUMEN.SITE Inc.