fireguy1125
asked on
Modify VBS/Batch Script to Terminate EXCEL.EXE Processes
I'm using a combination of the below scripts to rename an xlsx extension file to an xls extension file. I find that sometimes excel remains running and prevents the script from executing. I would like to include a line in either file to terminate all running instances of excel.exe so the script can process successfully. Presently, I'm going through the task manager to end the process manually.
Batch file:
VBS file:
Batch file:
C:\Scripts\xlsx2xls.vbs "C:\report.xlsx" "C:\report.xls"
VBS file:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(Wscript.Arguments(0))
objExcel.Application.Visible = False
objExcel.Application.DisplayAlerts = False
objExcel.ActiveWorkbook.SaveAs Wscript.Arguments(1), 56
objExcel.ActiveWorkbook.Close
objExcel.Application.DisplayAlerts = True
objExcel.Application.Quit
WScript.Quit
This script will terminate any orphan instances of Excel that are running:
Option Explicit
Dim objWMIService, objProcess, colProcess
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = " & "'EXCEL.EXE'")
For Each objProcess in colProcess
objProcess.Terminate()
Next
ASKER
Thanks, can I put those 10 lines of code just as they are, preceding what I have in my vbs file?
So should the following work?
So should the following work?
Option Explicit
Dim objWMIService, objProcess, colProcess
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = " & "'EXCEL.EXE'")
For Each objProcess in colProcess
objProcess.Terminate()
Next
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(Wscript.Arguments(0))
objExcel.Application.Visible = False
objExcel.Application.DisplayAlerts = False
objExcel.ActiveWorkbook.SaveAs Wscript.Arguments(1), 56
objExcel.ActiveWorkbook.Close
objExcel.Application.DisplayAlerts = True
objExcel.Application.Quit
WScript.Quit
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks, works perfect!
Glad to help.
objWorkbook.Close False
before closing Application.
HTH