Close a word document that is already open

Tornado1981

Board Regular
Joined
Apr 1, 2010
Messages
248
Hi,

I'm trying to check whether a specific word document is open or not. If open, then close it and first then reopen again and if not then just open it.

The problem is that I always get a Bad file name 4160 error when it tries to close the document.


Would anyone plz tell me where exactly is the problem in my code.


Thank u in advance.

Code:
Dim wdApp As Object
Dim myDoc As Word.Document
             
Set wdApp = GetObject(, "Word.Application")
            
If IsFileOpen(FilePath & "TemporaryLetter.docx") Then
    wdApp.Documents(FilePath & "TemporaryLetter.docx").Close
End If
            
With wdApp
    .Visible = True
    .WindowState = 2
End With
                
Set myDoc = wdApp.Documents.Open(FilePath & "TemporaryLetter.docx")
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
shg .. Nothing happens
Not discounting Norie's suggestion, but instead of

Code:
If IsFileOpen(FilePath & "TemporaryLetter.docx") Then
    wdApp.Documents(FilePath & "TemporaryLetter.docx").Close
End If

... perhaps

Code:
On Error Resume Next
wdApp.Documents("TemporaryLetter.docx").Close
On Error Goto 0
 
Upvote 0
Something wrong with Filename or FilePath, can you post a response of msgbox(FilePath & "TemporaryLetter.docx")
 
Upvote 0
This code works good:
Code:
Sub test()
Dim wdApp As Object
Dim myDoc As Word.Document
             
FilePath = "C:\Users\111\Desktop\"
Set wdApp = GetObject(, "Word.Application")
            
For Each myDoc In wdApp.Documents
If myDoc.Name Like "111.docx" Then wdApp.Documents(FilePath & "111.docx").Close
Next
               
Set myDoc = wdApp.Documents.Open(FilePath & "111.docx")
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,516
Messages
6,119,978
Members
448,934
Latest member
audette89

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top