310 Part II Programming Fundamentals
assigns a Boolean value of True if the document is found in the Documents collection. The
docLocation string variable contains the path of the MyLetter .doc file on disk. (This routine
assumes that the MyLetter .doc file is with your book sample files in C:\Vb10sbs\Chap12 .)
The For Each... Next loop cycles through each document in the Documents collection,
searching for the MyLetter file. If the file is detected by the InStr function (which detects one
string in another), the file is saved. If the file isn’t found, the macro attempts to open it by
using the Open method of the Documents object.
Also note the Exit For statement, which I use to exit the For Each... Next loop when the
MyLetter file has been found and saved. Exit For is a special program statement that you
can use to exit a For... Next loop or a For Each... Next loop when continuing will cause
unwanted results. In this example, if the MyLetter .doc file is located in the collection,
continuing the search is fruitless, and the Exit For statement affords a graceful way to stop
the loop as soon as its task is completed.
Entering the Word Macro
I’ve included this sample Word macro to show you how you can use collections in Visual
Basic for Applications, but the source code is designed for Word, not the Visual Studio
Integrated Development Environment (IDE). If you aren’t working in Word, the Documents
collection won’t have any meaning to the compiler.
The steps that you will follow to try the macro depend on the version of Word you are using.
If you are using Word 2007 or Word 2010, you’ll need to start Word, click the Developer tab,
click the Macros command, specify a name for the macro (I used OpenMyDoc), click Create,
and then enter the code by using the Visual Basic Editor. (If the Developer tab is not shown,
you will need to enable it in the Word Options dialog box .) If you are using Word 2003, you’ll
need to start Word, go to the Macro submenu of the Tools menu, click the Macros command,
specify a name for the macro, click Create, and then enter the code by using the Visual Basic
Editor.
In the Visual Basic Editor, the completed macro looks like the following screen shot. You can
run the macro by clicking the Run Sub/UserForm button on the toolbar, just as you would
run a program in the Visual Studio IDE. After the macro runs, click the Word application
again, and you’ll see that the MyLetter document has been opened for you.
Tip Word macros are generally compatible between versions, although I have sometimes run
into problems when upgrading VBA macros or supporting multiple versions of Office. If you are
using a different version of Word, you may need to slightly modify the sample code shown on
the following page.