Automating Word VB Help

Microsoft Word provides numerous objects which you can use to program any action that can be carried out with menu commands. For example, you can open a document, count words and characters, replace certain words in it, and save it back on disk without user intervention. You can actually do all this in background with even displaying Word’s window on the Desktop.

The top-level Word object is the Application object, which represents the current instance of the application. You can use the Application object to access some general properties of the Word’s window including its Visible property (to make the application visible or not) and the active document (to switch to one of the open documents).

Under the Application object is the Documents collection, which contains a Document object for each open document. Using an object variable of Document type, you can access any open document (or open and create new documents). The most important object that each document exposes is the Range object, which represents a contiguous section of text. This section can be words,. part of a word, characters, or even the entire document. Using the Range object’s methods, you can insert new text, format existing text (or delete it), and so on .

To address specific units of text, use the following collections:

• The Paragraphs collection, which is made up of Paragraph objects that represent text paragraphs
• The Words collection, which is made up of Word objects that represent words
• The Characters collection, which is made up of Character objects that represent individual characters.

For example, you retrieve all the paragraphs of a document through the Paragraphs collection of the Document object. If you apply the same method to the current selection (represented by the Selection object), you retrieve all the paragraphs in the selected text. In the following section, we arc going to explore the members of ·the basic objects exposed by Word and show you how to use them from within your Visual Basic code.

The Documents Collection and the Document Object

The first object under the Word Application object hierarchy is the Document object, which is any document that can be opened with Word or any document that can displayed in Word’s window. All open documents belong to a Documents collection that is made up of Document objects. Like all other collections, it supports the Count property (the number of open documents); the Add method, which adds a new document; and the Remove method, which closes an existing one. To access an open document, you can use the Item method of the Documents collection, specifying the document’s index as follows:

Application.Documents. Item(1)

Or, you can specify the document’s name:

Application.Documents.ltem(‘MasteringVB.doc’)

Since Item is the collection default property, you can omit its name altogether:

Application.Documents(1)

To open an existing document, use the Documents collection’s Open method, whose syntax is:

Documents.Open(fileName)

ThefileName argument is the document file’s path name.

To create a new document, use the Documents collection’s Add method, which accepts two optional arguments:

Documents.Add (template, newTemplate)

The argument template specifies the name of a template file to be used as the basis for the new document. The new template argument is a Boolean value. If it’s set to True, Word creates a new template file.

Most of the operations you’ll perform apply to the active document (the document in the active Word window), which is represented by the ActiveDocument object, a property of the Application object. To access the selected text in the active document, use the following expression:

Application.ActiveDocument.Selection

You can also make any document active by calling the Activate method of the Document object. To make the document MyNotes.doc active, use the following statement:

Documents(‘MyNotes.doc’).Activate

After the execution of this statement, the MyNotes.doc document becomes the active one, and your code can refer to it through the object Application.ActiveDocument.

Printing and Saving Documents

To print a document, call its Printout method, which has the following syntax:

All the arguments are optional and they correspond to the properties you can set on Word’s Print dialog box. The Background argument is an optional value that specifies whether the printout will take place in the background, and this argument is usually set to True when we’re automating applications.

When you use VBA to instruct Word to print a document, the process of spooling the document to the printer queue is not instantaneous. If you attempt to quit the application immediately after calling the Printout method, Word will inform you that quitting at this point will cancel the printout. To make sure that the document has been spooled (which means you can safely quit Word), you must set up a loop that examines the value of the BackgroundPrinting property, As long as this property is not 0, the application is busy spooling the document. After all the information has been queued, you can quit Word.

To save a document, use the SaveAs method of the Document object, which has. the following syntax:

As with the Print method, the arguments of the SaveAs method’s arguments correspond to the settings of the application’s Save As dialog box. If the file has been . saved already, use the Save method, which accepts no arguments at all. It saves the document to its file on disk using the options you specified in the SaveAs method when the document was saved for the first time. To save the active document under a different file name, use the following statement:

A related property of the Document object is the Saved property, which returns a True/False value indicating whether a document has been changed since the last time it was saved. Use the Saved property in your code to find out whether you must call the Save method before you quit the application.

The following code segment opens an existing document, prints it, and then quits. Notice that I use the Createobject() function to create a new instance of Word. I did this to simplify the code. You’ve already seen how to contact the existing instance of Word if it exists.

The BackgroundPrintingStatus property returns a non-zero value while Word is spooling the document. While the loop is executing, the application won’t quit.

Because of hardware errors, this process may never end, and we don’t want our application to lock up. Every minute, the program asks the user whether they want to wait or not. If the user decides to terminate the printout, the breakLoop Boolean variable is set to True from within the loop’s code and the While’loop breaks. This approach is rather simplistic and takes up too much computer time, It would be far more efficient to place a Tuner control on the Form and monitor printout’s progress from within the Timer event.

Objects That Represent Text

The basic object for accessing text in a Word document is the Range object, which represents a contiguous segment of text. To extract some text from a document, you can use the Document object’s Range method; which accepts as arguments the positions of the starting and ending characters in the text. The syntax of the Range method is:

Document.Range(start, end)

The start and end arguments are two numeric values. Oddly enough, the first character’s position in the document is 0; The following statement extracts the first 100 characters of the document represented by the Document object variable:

Range1 = Document.Range (0, 99)

These characters are assigned to the Range1 object variable. The Range1 variable can be a variant, but it can also be declared as  Range type:

Dim Range1 As Range

In the previous expressions, the Document variable must first be set to reference .an existing object with a statement like the following one:

Set Document1 = Documents(1)

The Document1 variable can.be a variant, or it must be declared as Document type:

Dim Document1 As Document

You can also replace the variable Document1 with the built-in object Active-Document, which represents the active document. The selected text in the active document can be accessed by the following expression:

Application.ActiveDocument. Selection

Words, sentences, and paragraphs are more meaningful units of text than characters. The Word, Sentence, and Paragraph objects are better suited for text manipulation, and you commonly use these objects to access documents. These’ objects, however, don’t support all the properties of the Range object. All units of text can be converted to a Range object with the Range property. For example, the following statement returns the third paragraph in the specified document as a Range object:

Document1.Paragraphs(3).Range

You can then access the Range object’s properties to manipulate the third paragraph.

The Paragraph object doesn’t have a Font property or a Select method. To change the appearance of the third paragraph in the document, you must first convert the paragraph to a Range object with a statement like the following one:

Document1 is a properly declared Document variable, and Range1 is a properly declared Range variable. You’can also combine both statements into one and avoid the creation of the Range1 object variable as follows:

Document1.Paragraphs(3).Range,Font.Bold = True

The following statement selects (highlights) the same paragraph:

Document.Paragraphs(3).Range.Select

Once a paragraph (or any other piece of text) is selected, you can apply all types of processing to it (e.g., edit it, move it to another location, format it).

The two methods of the Range object that you’ll use most often are InsertAfter, which inserts a string of text after the specified Range, and InsertBefore, which inserts . a string of text in front of the specified Range. The following statements insert a .title at the beginning of the document and a closing paragraph at the end:

The Select method of the ActiveDocument object selects the entire text. The selected text is then converted to a Range object, so that the Range object’s methods can be applied to it. The InsertBefore and InsertAfter methods place some text before and after the Range object.

VB6 at Work: The Word VBA Project

With the objects and methods described so far, you have enough information to create a new document, place some text into it, format it, and then save it to a disk file. The first step is to start an instance of Word and connect to it. The WordVBA project demonstrates how to:

• Create a new document.
•  Insert some text and format it.
• Count the. paragraphs, words, and’ characters in the new document and display them in a message box.

These actions take place from within the Visual Basic application while Word is running in the background. The user doesn’t see Word’s window, not even as an icon on the taskbar. The new document is saved as C:\SAMPLE.DOC and you can_open it later with Word and edit it.

The code behind the Create DOC File button is straightforward. It uses the Paragraph property of the Document object to manipulate the text (insert new paragraphs and manipulate them). Notice how it changes the alignment of the first text paragraph with the Alignment property of the Paragraph object.

The Massage DOC File button shows you how to manipulate the text in a Word document through OLE Automation. the initial text contains multiple spaces between words that shouldn’t be there. To reduce multiple spaces to single space characters (a task in editing), you can use the Find & Replace dialog box. The WordVBA Application does the same by calling the Find method.

The Find method accepts a large number of arguments, most them optional. For the WordVBA application we must specify the string to search for and the replacement string.The program searches for two consecutive spaces, and if found, replaces them with a single space. The process can’t end here, because the document may contain three consecutive spaces that need to be reduced to two. So the Find & Replace operations must continue. As long as the code finds two consecutive spaces, it repeats the replace operation and reduces them to one space.

Spell-Checking Documents

One of the most useful features of Word (and of every Office application) is its ability to spell-check a document, This functionality is also exposed by Word’s VBA objects, and you can borrow it for use within your Visual Basic applications. This is not only possible, it’s actually quite simple. To call upon Word’s spell-checking routines, you need to know about two objects: the ProofReadingErrors collection and the SpellingSuggestions collection.

The ProofReadingErrors collection is a property of the Range object and it contains the misspelled words in the Range. To ask Word to spell-check a range of text and populate the ProofReadingErrors collection, call the Range object’s Spelling- Errors method. This method returns a result that must be stored in an object variable of type ProofreadingErrors:

ORange is Range object (a paragraph or an entire document). The second Me populates the SpellCollection variable with the misspelled words. You can then set up a For Each Next loop to read the words from the collection.

Besides locating spelling errors, Word can also suggest a list of alternate spellings or words that sound like the misspelled one. To retrieve the list of alternate words, you call the GetSpellingSllggestions method of the Application object, passing the misspelled word as an argument. Notice that this is a method of the Application object, not of the Range object you’re spell-checking. The results returned by the GetSpellingSuggestions method must be stored in a similar object variable, whose declared type is SpellingSuggestions:

The second line.retrieves the suggested alternatives for the word android. To scan the list of suggested words, you set up a loop that retrieves all the elements of the Correctionstlollection collection. The example in the next section demonstrates the use of both methods from within a Visual Basic application.

VB6 at Work: The SpellDoc Project

spellDoc is an application that uses Word’s methods to spell-check a document. You’ll find the SpellDoc application in this chapter’s folder on the CD. The application’s main Form, shown in Figure 14.15, consists of a multi-line TextBox control on which the user can enter some text (or paste text from another application) and spell-check it by clicking the Spell Check Document button.

The application will contact Word and request the list of misspelled words. The list of misspelled words will be displayed on a different Form, shown. The ListBox control on the left shows all the misspelled words returned by Word. Word Cannot only locate misspelled words, but suggest alternatives as well. To view the alternate spellings for a specific word, select the word in the left list with the mouse.

To replace all instances of the selected misspelled word with the selected alternative, click the replace button. You can design your own interface to allow the user to select which and how many instances of the misspelled word in the original document will be replaced.

The program uses three public variables, which are declared as follows:

The SpellCollection variable is a collection that contains all Ute misspelled words, and the CorrectionsCollection variable is another collection that contains the suggested spellings for a specific word. The CorrectionsCollection variable’s contents are assigned every time the user selects another misspelled word in Word’s Spelling Suggestion window.

When the SpellCheck Document button is clicked, the program contacts the Word application. First, it attempts to connect to an existing instance of.Word with the GetObject() function. If no instance of Word is currently running it starts a new instance of Word. This is done with the following lines in Code.

After contact with Word is established, the program creates a new document and Copies the TextBox control’s contents to the new document using the Insert- After method of the Range object, as follows:

AppWord.Documents.Add
DRange.InsertAfter Text1.Text

Now comes the interesting part.The VlSUal Basic code calls the Range object’s, ,SpellingErrors method, which returns a collection of Word objects. The result of the SpellingErrors method is assigned to the object variable SpellCollection:

Set SpellCollection = DRange.SpellingErrors

The following lines add the words contained in the SpellCollection variable to the left.list of the second Form and then they display the Form.

On the second Form of the application, all the code is concentrated in the Words in Question list’s Click event. Every time an entry in this listBox is clicked, the code calls the App Word object’s GetSpellingSuggestions method, passing the selected word as an argument. Notice that we add 1 to the list’s Listlndex property to offset the fact that the indexing of the elements of a collection starts at 1, while the indexing of , the elements of a listBox control starts at O. The GetSpellingSuggestions method returns another collection with the suggested words, which are placed in the second ListBox control on the Form with the following statements.

The SpellDoc application can become the starting point for many custom Visual Basic applications that require spell-checking, but don’t need powerful editing features. In some cases, you might want to customize spelling, although it’s not a very common situation. In a mail-aware application, for example, you can spell-check the text and exclude URLs and e-mail addresses. You would first scan the words returned by the SpellingErrors method to check which ones contained special characters and omit them.

As you can see, tapping into the power at the Office applications isn’t really complicated. Once you familiarize yourself with the objects of these applications, you can access the Office applications by manipulating a few properties and calling the methods of these objects.

Posted on November 6, 2015 in OLE Automation and VBA

Share the Story

Back to Top