Share this Page URL

Chapter 40. Building Custom Applications... > Opening, Closing, and Creating New D... - Pg. 960

Building Custom Applications with VBA · To display a complete list of built-in Word commands, choose Tools, Macro, Macros; then choose Word Commands from the Macros In drop-down list. 960 Opening, Closing, and Creating New Documents The most fundamental VBA commands look similar in Word, Excel, PowerPoint, and FrontPage-- and very different in Outlook and Access. Using VBA to Open, Close, and Create Word Documents In Word, the command to create a new document based on the normal document template (Nor- looks like this: Documents.Add If you want to base the new document on a different template, add the full path to the template: Documents.Add "c:\ Program Files\ Microsoft Office\ Templates\ Company\" To open an existing file--C:\ My Documents\ Invoice1049.doc, for example--use the Open method: Documents.Open "C:\ My Documents\ Invoice1049.doc" The Open method not only opens the document, it makes the newly opened document the active document--just as Word would, if you opened it by choosing File, Open. There are three common ways to save a document. If you just want to save the currently active document, use ActiveDocument.Save On the other hand, if you know you want to save the document called "Memo to Justin.doc"--but you don't know whether it's the currently active document, you can activate it, and then close it, like this: Documents("Memo to Justin.doc").Activate ActiveDocument.Save In fact, VBA/Word doesn't require you to activate the document before you save it. This will save "Memo to Justin.doc," too: Documents("Memo to Justin.doc").Save The Close method works just like the Save method. All three of these are valid: ActiveDocument.Close Documents("Memo to Justin.doc").Activate ActiveDocument.Close Documents("Memo to Justin.doc").Close That looks pretty simple, but there's a lot behind the different commands. In VBA parlance, a Docu- ment is an object. In this case, the Document object is exactly what you would expect: a Word document. The Documents object is a collection of Document objects; more precisely, it's the collection of open Word documents. Documents("Invoice.doc") is the Document object called In- voice.doc.