-1

I have this VB script in Excel that creates a Word document from an Excel File.

However, whenever I re-run the same script, I get a prompt that the Word file is Open and Locked for Editing. I manually go to Task Manager and End all open Word processes. Is there a script to check if a specific Word file is Open, and if it is, it will kill the process?

1 Answers1

1

Before creating the word document, you can can close the process WINWORD.EXE by placing the following code:

CreateObject("WScript.Shell").Run "taskkill /f /im WINWORD.EXE", 0

After doing this, you can proceed with the word file creation. Even if there are multiple processes running, they are all terminated.

Here, /f indicates the forceful deletion of process and /im indicates that we are passing the process name(WINWORD.EXE in this case).

To know more about the taskkill command, you can refer this site: https://technet.microsoft.com/en-in/library/bb491009.aspx

EDIT 2: If there are multiple documents open and you want to close only one of them then, you can write the following codes to close that particular document:

Case 1: When you know the exact path of the word file to be closed

strPath = "store the word file path in this variable"

set objDoc = getobject(strPath)
objDoc.close

set objDoc = Nothing

Case 2: When you only know the name(let's say the name is Document1) and not the path

set objWord = getobject(,"word.application")
set objDocs = objWord.Documents
for each doc in objDocs
    If strComp(doc.name,"Document1",1)=0 then
        doc.close
        Exit For     
    End If
next
set objDocs = Nothing
set objWord = Nothing
Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43