VBA to identify and close the instance of word which opened a word file that is only identified by its full path and file name

1. My excel 2010 project has an inventory list of word files incl paths.

2. Before moving/copying one word file (myWordFile.docx) between folders, myWordFile.docx must be closed via vba (if it is open).  However, I also need to close the  instance of the word application that opened myWordFile.docx, without closing other instances of word that may be running other unrelated documents, not necessarily run from the excel inventory.

Do I to enumerate the available instances of word (I dont know how), find which one opened myWordFile.docx, close the doc and quit that word instance? Or is there another way of getting the word instance by some indirect referencing via myWordFile.docx, and then closing doc and quitting app?

I've not done this before, and seek a code solution not only a choice of approaches.

[For reference (and it may not be relevant to the current purpose, the options  for closing myWordFile.docx from its path and filename alone are explored in:  http://www.experts exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/Word/Q_28684594.html.]

Thank you

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Not at a computer right now but something like:
Kelvin4Author Commented:
The context is more complex...
"...  I also need to close the  instance of the word application that opened myWordFile.docx, without closing other instances of word that may be running other unrelated documents..."
I think you will have to try using the window id from hwnd...


Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Or try getActiveWindow - https://msdn.microsoft.com/en-us/library/windows/desktop/ms646292(v=vs.85).aspx
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Hi Kelvin,

Closing Word instance might cause other word files opened under that instance to close too. Do you really need something like this?
Kelvin4Author Commented:
Thanks, Tilsant.
This project is a file repository for WORD docs. Correct me if I'm wrong, but is not each word doc opened in a separate instance of word? So I thought that I could EITHER:
- enumerate through the word instances and pick the one that has the doc I need to close - and close doc and instance,
- use the path+name of a file I need to close, and use GetObject to get its doc.object, and then use doc.application to get its word instance. Then close the doc and quit the Word instance.

My problems are:
1. I've not done this before
2. I may be wrong about both options
3. I'd like to get the right methods..

Thanks for forcing me to clarify my case and expose my ignorance..

Kelvin4Author Commented:
Thanks for your followup: I hope my response to Tilsant helps.
I dont know whether the choices I suggest are sensible or possible.
Nor do I know the syntax for Word.
At the end of the day - I'm seeking advice based on a testable coded procedure, because I'm not experienced enough to rely on my own coding at the level of Window/applications/handles/GetObjects etc...

Hi there,

Word typically opens all documents in the same instance (I think this is different to Excel?) but it is certainly possible to force Word to open a document in a new instance...

It is reported - I think by Shauna Kelly, but certainly a MS-Word-MPV, that word's document collection is buggy... at any rate that is certainly my experience.   In practice you should be able to get a list of all documents that are open, but it does not always work...  

Sorry - not able to develop or test any code right now...   later maybe :-)
Kelvin4Author Commented:
Thanks for your comments and warnings.
Kelvin4Author Commented:
Many thanks; I should have thought about widening the topics.
Hi Kelvin,

Absolutely forgot about this thread!

In the default case, all word files open in the same instance, until and unless we force a new Word instance and then open a document through it - either manually or programmatically.

Continuing to my earlier solution on checking if the word file is open or not, below is the revised version, which will close the word file if found open and close the word instance only if that single word file was open in that instance, else it'll leave the word instance as it is.

Sub CloseWordFile_If_Open(filename As String)

    Dim iFilenum As Long
    Dim iErr As Long
    Dim wdApp As Object
    Dim varTemp As Variant

    On Error Resume Next
    iFilenum = FreeFile()
    Open filename For Input Lock Read As #iFilenum
    Close iFilenum
    iErr = Err
    On Error GoTo 0

    If iErr = 70 Then
        On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
        On Error GoTo 0
        If wdApp Is Nothing Then
            Exit Sub
        End If
        varTemp = wdApp.documents.Count
        If varTemp > 0 Then
            For i = 1 To varTemp
                If wdApp.documents(i).FullName = filename Then
                    wdApp.documents(i).Close (False)
                    If varTemp = 1 Then wdApp.Quit
                    Exit Sub
                End If
        End If
    End If

End Sub

Open in new window

Hope this helps.
- tilsant

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kelvin4Author Commented:
Dear Tilsant,
Many thanks for carrying this question forward.
I apologise to you and Mr Wolfe for my delay in this response; I was out of reach of the web.

Kind regards
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Word

From novice to tech pro — start learning today.