Reputation: 53
I am having trouble closing a Word document with VBScript. When the Word document is opened (by the script) a temporary ~$ file is created by Word. For example, opening test.docx also creates a temporary file called ~$test.docx. I understand this is normal. But the problem is that when I close test.docx, the main document test.docx closes properly but ~$test.docx is left behind still open. With many files to process there is soon a large number of these temporary files. They show up in task manager as a background process. What am I doing wrong in closing the files? The code I am using is:
Set objWord = CreateObject("Word.Application")
objWord.Visible = False
objWord.DisplayAlerts = 0
objWord.Documents.Open FilePath 'FilePath previously set
'Do stuff (reading properties)
objWord.Documents.Close 0 'Close opened documents without saving
objWord.Quit
Set objWord = Nothing
Upvotes: 3
Views: 1863
Reputation: 61028
It could be that the objWord
variable is a 'global' reference to the Word application, defined somewhere at the top of the script.
This global reference remains in place as long as the calling program is active because the operating system will not end the automated application while the caller is active.
If that is the case here, wrapping the code in a function and defining the word object in there should solve it, because then the object has local scope and does not exist outside the function.
Something like this:
Function DoWordThings(FilePath)
Dim oWord
Set oWord = CreateObject("Word.Application")
oWord.Visible = False
oWord.DisplayAlerts = 0
oWord.Documents.Open FilePath 'FilePath now used as parameter to the function
'Do stuff (reading properties and returning them to the caller of this function)
oWord.Documents.Close 0 'Close opened documents without saving
oWord.Quit
Set oWord = Nothing
End Function
Upvotes: 2