Link to home
Start Free TrialLog in
Avatar of fireguy1125
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:
C:\Scripts\xlsx2xls.vbs "C:\report.xlsx" "C:\report.xls"

Open in new window


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

Open in new window

Avatar of pablito70
pablito70

Try to add

objWorkbook.Close False

before closing Application.

HTH
Avatar of Joe Howard
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

Open in new window

Avatar of fireguy1125

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?

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

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Joe Howard
Joe Howard
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks, works perfect!
Glad to help.