I experienced an interesting (or should that be frustrating) problem recently during an Office 2010 migration.
We have some code in Word that saves the current document into Autonomy WorkSite. The code works by doing a Save As of the current document to a temporary file, and then saving the document again to free up the first file, which is then imported or checked-in into WorkSite, all pretty standard stuff.
The code has been working fine in 2010 until we changed the default document format for Word from DOCX to DOC. As soon as we changed the document format, Word continues to hold both documents open, and therefore the import/check-in process for WorkSite fails with a “The process cannot access the file because it is being used by another process” error (the error number is -2147221472)
You can easily replicate the issue with the following VBA code which saves the current active document to two different temp files, and then tries to delete the first file:
Sub SaveAsDemo()
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc1.doc”)
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc2.doc”)
Kill(Environ(“TEMP”) & “\TestDoc1.doc”)
End Sub
If you have the “Save files in this format” setting set to Word Document (*.docx), the code will run fine. Now change the setting to Word 97 – 2003 Document (*.doc) and run the code, and you’ll get a Run-time Error (70), Permission denied. If you look in the temp directory, you’ll see both files are still open (they have corresponding Word temp files)
So how do you get around this “undocumented feature”?
I found a couple of blog posts that mentioned that it’s just a matter of timing, and a pause would fix this issue. In my testing, this didn’t work (since it didn’t work when I just step through the code)
What I did find that worked was just doing it all twice! So the following code works a treat:
Sub SaveAsDemo()
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc1.doc”)
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc2.doc”)
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc1.doc”)
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc2.doc”)
Kill(Environ(“TEMP”) & “\TestDoc1.doc”)
End Sub
No idea why this works – it just does!
So in the production code I added a check to see what the default save format was, and did an extra lot of saves if it was set to Doc.
Sub SaveAsDemo()
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc1.doc”)
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc2.doc”)
If Application.DefaultSaveFormat = “Doc” Then
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc1.doc”)
ActiveDocument.SaveAs2(Environ(“TEMP”) & “\TestDoc2.doc”)
End If
Kill(Environ(“TEMP”) & “\TestDoc1.doc”)
End Sub
And there you have it, a dodgy workaround around for a very dodgy problem. Hopefully it’ll get fixed one day soon (but where would the fun in that be!)