![]() |
|
#1
|
|||
|
|||
|
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
Last edited by scienceguy; 12-12-2021 at 10:50 AM. |
|
| Tags |
| open file |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| VBA to save open word file with name created from words in file | Lord Jim | Word VBA | 4 | 09-02-2021 02:33 PM |
| Every Folder I open goes into File Explorer but when I click on a file it won't open | bird dog | Word | 3 | 10-08-2019 10:03 AM |
| Word-OneDrive-Excel link not working when Word file re-opens | Prakash-Gautam | Word | 0 | 05-02-2019 07:35 PM |
I am unable to open documents in Word through their file location, only via Word itself (Word 2013)
|
Duke | Word | 5 | 07-31-2015 08:30 AM |
| Desktop word doc 2002 shortcuts not working right; will open word but not doc | Forensics1 | Word | 2 | 03-19-2014 02:26 PM |