Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"Close Word Document If Open" Through Macro Code

Status
Not open for further replies.

jtrapat1

Programmer
Jan 14, 2001
137
0
0
US
We have a word macro which generates a word document, opens it, and then "Save As" with a specified filename.
The word document is launched from a hyperlink on a web page.

The problem is if the user has this document open and it is minimized somewhere on the screen, the user cannot click on the link again to run the macro until this document is closed.
If he does, it will cause an error.

We have the filename but we need a check to see if this file is open; and if so, we need to close the word document before we save it.

Does anyone know of any vba code to perform this check?

Thanks in Advance.
John
 
Are you executing this code from within Word VBA? If so, why not just do

on error resume next
documents("MyDoc.doc").close
on error goto 0

Rob
[flowerface]
 
Thanks Rob,

Right now, we do pop up a message box if the document is already open.
I thought there might be a way thru code in which we could compare file names and then...
If that document is open, we could close it and then re-open it.

Here's the current macro code:
--------------------------------------------------
FileNm = "C:\YB.doc"
WordDoc.SaveAs FileName:=FileNm, FileFormat:=wdFormatDocument, _
LockComments:=False, Password:="", AddToRecentFiles:=True,
WritePassword _
:="", ReadOnlyRecommended:=True, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False,
SaveAsAOCELetter:=False

Application.Visible = True

Err_Handler:
If Err.Number = 5356 Then
MsgBox "Error! You have a YB open. Please close [" & FileNm & "]
then run it again!"
Application.Quit False
Exit Sub
End If
----------------------------------------------

Thanks
John
 
John,
The code I suggested above accomplishes what you need, I think. It attempts to close the document (before you try to save a new one under that name). If it doesn't exist, an error will occur, but due to the on error resume next, that will not interrupt code execution.
If you really want to do an explicit check first, you could do:

FileOpen=false
for i=1 to documents.count
FileOpen=FileOpen or (ucase(documents(i).name)="YB.DOC")
next i
if FileOpen then
'the file was already open
documents("YB.DOC").close
end if

Rob
[flowerface]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top