Opening an Existing Word Document

The CenterText procedure that follows demonstrates the use of the GetObject function to access the Invite.doc file. As you recall, this file was created earlier in this chapter by the WriteLetter procedure. The CenterText procedure will center the first paragraph in the specified Word document. The procedure uses a custom function named DocExists to check for existence of the specified document. Another custom function (IsRunning) checks whether the copy of Microsoft Word is already running. Based on the findings, the CreateObject or GetObject functions are used. If an error occurs, the error number and error description are displayed.

Sub CenterText() Dim wordDoc As Word.Document Dim wordAppl As Word.Application Dim mydoc As String Dim myAppl As String

On Error GoTo ErrorHandler mydoc = "C:\Invite.doc" myAppl = "Word.Application"

'first find out whether the specified document exists If Not DocExists(mydoc) Then

MsgBox mydoc & " does not exist." & Chr(13) & Chr(13) _ & "Run the WriteLetter procedure to create " & mydoc & "." Exit Sub End If

'now check if Word is running If Not IsRunning(myAppl) Then

MsgBox "Word is not running - will create a new instance of _ Word. "

Set wordAppl = CreateObject("Word.Application") Set wordDoc = wordAppl.Documents.Open(mydoc)


MsgBox "Word is running - will get the specified document. " 'bind the wordDoc variable to a specific Word document Set wordDoc = GetObject(mydoc) End If

'center the 1st paragraph horizontally on page With wordDoc.Paragraphs(1).Range

.ParagraphFormat.Alignment = wdAlignParagraphCenter

End With wordDoc.Application.Quit SaveChanges:=True Set wordDoc = Nothing Set wordAppl = Nothing

MsgBox "The document " & mydoc & " was reformatted." Exit Sub ErrorHandler:

MsgBox Err.Description, vbCritical, "Error: " & Err.Number End Sub

Function DocExists(ByVal mydoc As String) As Boolean On Error Resume Next If Dir(mydoc) < > "" Then DocExists = True


DocExists = False End If End Function

Function IsRunning(ByVal myAppl As String) As Boolean Dim applRef As Object On Error Resume Next

Set applRef = GetObject(, myAppl) If Err.Number = 429 Then IsRunning = False


IsRunning = True End If

'clear object variable Set applRef = Nothing End Function

0 0

Post a comment