Error Handling on Opening Word Document

zooropa66

Registered User.
Local time
Today, 16:55
Joined
Nov 23, 2010
Messages
61
I have the following code snippet that opens up word document T163.doc from C:\MyTCN\

When the file exists it opens up.

When it doesn't exist it throws out an error message box with a load of info and a Debug button.

However, I'd just like it to pop up a message box saying "File Does Not Exist"

I've tried playing around but can't achieve this as I'm not overly confident with error handling.

Any help would be greatly appreciated.

Code:
Private Sub TCN_Click()

'In order to use this code you must set a reference to the
'Word object library by doing this. In the VB Editor click
'Tools, References. Then search for Microsoft Word n.n Object Library
'where n.n will depend on your version of Word.

Dim wdApp As Word.Application, wdDoc As Word.Document

var_tcn_hyperlink = "C:\MyTCN\T163.doc"

On Error Resume Next

Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If

On Error GoTo 0

Set wdDoc = wdApp.Documents.Open(var_tcn_hyperlink)

wdApp.Visible = True

End Sub
 
Perhaps ask the file system if the file exists first rather than fire up an instance of Word to perform that simple check for you.

Code:
Function fsutils_FileExists(ByVal strFile As String, Optional ByVal bFindFolders As Boolean) As Boolean 
    'Purpose:   Return True if the file exists, even if it is hidden. 
    'Arguments: strFile: File name to look for. Current directory searched if no path included. 
    '           bFindFolders. If strFile is a folder, FileExists() returns False unless this argument is True. 
    'Note:      Does not look inside subdirectories for the file. 
    'Author:    Allen Browne. http://allenbrowne.com June, 2006. 
    Dim lngAttributes As Long 
 
    'Include read-only files, hidden files, system files. 
    lngAttributes = (vbReadOnly Or vbHidden Or vbSystem) 
 
    If bFindFolders Then 
        lngAttributes = (lngAttributes Or vbDirectory) 'Include folders as well. 
    Else 
        'Strip any trailing slash, so Dir does not look inside the folder. 
        Do While Right$(strFile, 1) = "\" 
            strFile = Left$(strFile, Len(strFile) - 1) 
        Loop 
    End If 
 
    'If Dir() returns something, the file exists. 
    On Error Resume Next 
    fsutils_FileExists = (Len(Dir(strFile, lngAttributes)) > 0) 
End Function
Sample code of driving Word from Access:

Example Access VBA preparing a Word document using Range Bookmarks
http://www.access-programmers.co.uk/forums/showthread.php?t=236469
 

Users who are viewing this thread

Back
Top Bottom