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

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
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,224,803
Messages
6,181,055
Members
453,015
Latest member
ZochSteveo

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