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 and Save a file if it is open 1

Status
Not open for further replies.

gogopoppy

Instructor
Mar 6, 2005
114
CA
Hi,

I need to automatically check if an Excel file is open and if it is I want to close and save it or just close it without saving changes.

I can do VBA but new to VBScript, so I understand things like Option explicit and Dims.

The excel file is on the machine (Win2003 Server) where I would run my VBSCript.

Any help would be greatly appreciated

Thanks

Grd
 
Here is an example that you can use as a starting point.
This code will find and close an open Excel workbook.

Note that as is, although this code can handle multiple instances of Excel, the workbook you are looking for must be the active workbook in the particular instance of Excel in which it is contained.

So if you have multiple workbooks open in one instance of Excel, you will probably need to handle them as a collection, and find the correct workbook.

Code:
strName = "test.xls"
strPath = "C:\"
strFilePath = strPath & strName
wscript.echo "Name and path of Excel file to find and close: " & strFilePath

Set objExcel = GetObject(strFilePath).Application 'Use this syntax for multiple instances of Excel.

If (not objExcel.ActiveWorkbook is nothing) then
	wscript.echo "ActiveWorkbook is: " & objExcel.ActiveWorkbook.Name
		If objExcel.ActiveWorkbook.name = strName then
			wscript.echo "Closing Workbook " & strName 
			objExcel.ActiveWorkbook.Saved = True
			objExcel.ActiveWorkbook.Close		
		End if
	Else
		wscript.echo "Open Workbook " & strName & " Not Found"
End if

set objExcel=nothing

Hope this helps.
 
With the testing I've done it works. The file gets closed if its open. I removed the wscript.echo so it runs unaided.

Tx again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top