How to manage Word from Access

A

Al

I have an Access process where I open Word documents and print them.
Occassionally something goes bad and the process has to close down
cleanly--close the Word document if open, close word if opened by the process.

How can I be sure I am always looking at the document I have opened? If
word was already open I do not want to close that document and word.

The set prps line doesn't seem to be correct, and the ErrorHandler doesn't
always seem to close MS Word or the document consistently as I desire.

This is my code:

Public AppWord As Object
Public Docs As Object
Public ActDoc As Object
Public prps As Object
dim strSched as String

Private Sub Process_Click()
On Error GoTo ErrorHandler

call SetVars 'set transfer vars
Call WordOpen 'Open MSWord and document
Set prps = ActDoc.CustomDocumentProperties
prps.Item("strFirstName").Value = strFirstName
prps.Item("strLastName").Value = strLastName
Call PrintWordFile

ErrorHandlerExit:
Set prps = Nothing
Set AppWord = Nothing
Set Docs = Nothing
Set ActDoc = Nothing
Exit Sub

ErrorHandler:
binErrExit = True
Select Case Err.Number
Case "3021" 'Invalid Variables
MsgBox "Invalid Variables. Check for missing entries"
Me.NameType.SetFocus
Resume ErrorHandlerExit
Case Else
If IsWordOpen = False Then
AppWord.Quit
End If
MsgBox "From Process_Click: " & Err.Description, vbExclamation,
"Error No: " & Err.Number
Resume ErrorHandlerExit
End Select
End Sub

Sub WordOpen()
On Error Resume Next

WordOpenSuccessful = False
Set AppWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
' Debug.Print "Err.Number = " & Err.Number
IsWordOpen = False
Set AppWord = CreateObject("Word.Application")
Else
IsWordOpen = True
End If
Debug.Print "IsWordOpen = " & IsWordOpen

Set Docs = AppWord.Documents
Docs.Add strSched
Set ActDoc = AppWord.ActiveDocument

Exit Sub
 
R

Randall Arnold

Make the document you've started the ActiveDocument after it's loaded.

Also, I'd change WordOpen to a Function from a Subroutine. It'll simplify
your code a bit.

Randall Arnold
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top