Visual Studio Tools for Office: Using Visual Basic 2005 with Excel, Word, Outlook, and InfoPath

The Documents collection, available from the Application object's Documents property, contains a collection of Document objects open in Word. It also has methods used to access a Document in the collection, create a new document, open an existing document, close all the documents, and save all the documents.

Iterating over the Open Documents

The Documents collection can be iterated over using a For Each loop in Visual Basic 2005. Listing 8.18 shows a simple example of iterating over the open documents in Word and printing the name of each document to the console.

Listing 8.18. Iterating over the Documents Collection Using For Each

For Each doc As Word.Document In Application.Documents Console.WriteLine(doc.Name) Next

Accessing a Document in the Documents Collection

To access a Document in the Documents collection, you use the Item property, which returns a Document object. The Item property has an Index parameter passed by reference that is of type Object. You can pass an Integer representing the 1-based index of the document in the collection you want to access.

Alternatively, you can pass a String representing the name of the document you want to access. The name you pass for a document is the full name of the file, if it has been saved (for example, "c:\Documents and Settings\John\Desktop\Doc1.doc"). If the document has not yet been saved, the name to pass is the temporary name that Word creates for a new document. This temporary name is typically something like Document1, with no file extension. Listing 8.19 shows an example of calling Item with a 1-based index and a String index.

Listing 8.19. A VSTO Customization That Uses Item to Get a Document

Public Class ThisDocument Private Sub ThisDocument_Startup(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Startup ' Add 5 documents Dim i As Integer For i = 0 To 5 Application.Documents.Add() Next ' Iterate over the open documents using For Each For Each doc As Word.Document In Application.Documents MsgBox(doc.Name) Next ' Get a document by 1-based index. Dim index As Integer = 2 Dim doc1 As Word.Document = Application.Documents.Item(index) MsgBox(String.Format("The document at index {0} is {1}.", _ index, doc1.FullName)) ' Get a document by full name Dim doc2 As Word.Document = Application.Documents.Item(index) MsgBox(String.Format( _ "The document at string index {0} is {1}.", _ doc1.FullName, doc2.FullName)) End Sub End Class

You can also use the Count property to determine the number of open documents. You should check the Count property before accessing a document by index.

Creating a New Document

To create a new document, you can use the Documents collection's Add method. The Add method returns the newly created Document object. It takes four optional by reference parameters of type Object, as described in Table 8.5.

Table 8.5. Optional Parameters for the Documents Collection's Add Method

Parameter Name

What It Does

Template

Pass the short name of the template to be used (for example, "mytemplate.dot") if the template is in the Templates collection. If the template is not in the Templates collection, pass the full filename to the template (for example, "c:\mytemplates\template1.dot"). If you omit this parameter, Word uses the Normal template.

NewTemplate

Pass the Boolean value TRue if the document should be opened as a template. The default is False.

DocumentType

Pass a member of the WdNewDocumentType enumeration: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default is wdNewBlankDocument.

Visible

Pass the Boolean value true if the document should be opened in a visible window. The default is true.

Opening an Existing Document

To open an existing document, use the Documents collection's Open method, which returns the opened Document object. The Open method takes one required Object parameter, to which you pass the String representing the filename to open. The Open method also takes 15 optional by reference parameters of type Object, as described in Table 8.6.

Table 8.6. Optional Parameters for the Documents Collection's Open Method

Parameter Name

What It Does

ConfirmConversions

Pass true to display the Convert File dialog box if the filename passed to Open is not in Microsoft Word format.

ReadOnly

Pass TRue to open the document as read-only. If the document is already set to read-only on disk, passing False will not affect the read-only status of the document. The default is False.

AddToRecentFiles

Pass true to add the filename to the list of recently used files in the File menu. The default is TRue.

PasswordDocument

Pass a String representing the password for opening the document if the document is password-protected.

PasswordTemplate

Pass a String representing the password for opening the template if the template is password-protected.

Revert

If the document you are opening with the Open method is already open in Word, pass true to discard any unsaved changes in the already-open document. Pass False to activate the already-open document.

WritePasswordDocument

Pass a String representing the password for saving changes to the document if the document is password-protected.

WritePasswordTemplate

Pass a String representing the password for saving changes to the template if the template is password-protected.

Format

Pass a member of the WdOpenFormat enumeration specifying the file conversion to be used when opening the document.

Encoding

Pass a member of the Office.MsoEncoding enumeration specifying the code page or character set to be used when you open the document.

Visible

Pass true to open the document in a visible window. The default is true.

OpenConflictDocument

Pass true to open the conflict file for a document that has offline conflicts.

OpenAndRepair

Pass true to try to repair a corrupted document.

DocumentDirection

Pass a member of the WdDocumentDirection enumeration specifying the horizontal flow of text in the opened document.

NoEncodingDialog

Pass true to prevent Word from displaying the Encoding dialog box if the text encoding of the document cannot be determined.

Listing 8.20 shows the simplest possible way to call the Open method to open a document.

Listing 8.20. A VSTO Customization That Uses the Open Method to Open a Document

Public Class ThisDocument Private Sub ThisDocument_Startup(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Startup Dim doc As Word.Document = Application.Documents.Open("c:\test.doc") MsgBox(String.Format("Just opened {0}.", doc.Name)) End Sub End Class

Closing All Open Documents

The Close method on the Documents collection closes all the open documents in Word. It takes three optional parameters of type Object by reference. The first optional parameter, called SaveChanges, is of type Object and can be passed a member of the WdSaveOptions enumeration: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges. The second optional parameter, called OriginalFormat, is of type Object and can be passed a member of the WdOriginalFormat enumeration. The second parameter controls Word's behavior when saving a changed document whose original format was not Word document format. This parameter can be passed wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument. The final optional parameter is called RouteDocument and is of type Object. Passing true for this parameter routes the document to the next recipient if a routing slip is attached.

It is also possible to close an individual document using the Document object's Close method, as discussed later in this chapter. You have already learned how to use the Application object's Quit method as a third way to close all open documents and quit Word. The Quit method takes the same parameters as Documents.Close and Document.Close.

Saving All Open Documents

The Save method on the Documents collection saves all the open documents in Word. It takes two optional parameters. The first optional parameter, called NoPrompt, is of type Object and can be set to true to have Word automatically save all open documents without prompting the user. The second optional parameter, called OriginalFormat, is of type Object and can be passed a member of the WdOriginalFormat enumeration. The second parameter controls Word's behavior when saving a changed document whose original format was not Word document format.

It is also possible to save an individual document using the Document object's Save or SaveAs method, as discussed later in this chapter.

Категории