Hello,
I am writing an application, where several
individual routines are run on the same file. The code is organized where the user examines the Word document at the conclusion of each routine. Prior to starting the next routine, I would rather not have to close the file but just run the next routine on the already open file. Ultimately, they should have a choice, use a file already open or open a new file.
I have developed the following code, which *appears* to be working. However, every once in a while, the code gets hung up and stops working. I'm just curious if the code should work as is or is there a better way to accomplish this?
Thank you in advance for any help!
Roy
Code:
Sub testStart()
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
If IsFileOpen("c:\documents\my_file.docx") = False Then 'Word file is not open
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = False
End If
Set wdDoc = wdApp.Documents.Open(fileName:="c:\documents\my_file.docx", AddToRecentFiles:=False, Visible:=False)
Else 'Word file is open
Set wdApp = GetObject(, "Word.Application")
wdApp.Documents("my_file.docx").Activate
Set wdDoc = wdApp.ActiveDocument
End If
'move forward with application
End Sub
Function IsFileOpen(fileName As String)
'https://exceloffthegrid.com/vba-find-file-already-open/
Dim fileNum As Integer
Dim errNum As Integer
'Allow all errors to happen
On Error Resume Next
fileNum = FreeFile()
'Try to open and close the file for input.
'Errors mean the file is already open
Open fileName For Input Lock Read As #fileNum
Close fileNum
'Get the error number
errNum = Err
'Do not allow errors to happen
On Error GoTo 0
'Check the Error Number
Select Case errNum
'errNum = 0 means no errors, therefore file closed
Case 0
IsFileOpen = False
'errNum = 70 means the file is already open
Case 70
IsFileOpen = True
'Something else went wrong
Case Else
IsFileOpen = errNum
End Select
End Function