As Bathsheba already pointed out, Set fso = Nothing
and app.Quit
belong at the end of the script (outside the loop). There are some more bugs, though.
wb.SaveAs "*.xls*"
You can't save a workbook to a wildcard name. If you want to save the workbook under its current name, just use wb.Save
. Otherwise you'll have to use an explicit name (you should also set the filetype then):
wb.SaveAs "new.xlsx", 51
or
wb.SaveAs "C:\path\to\new.xls", -4143
wb.Close SaveChanges=True
VBScript doesn't support named parameters (see here). If you want to call the Close
method with the SaveChanges
parameter set to True
you have to do it like this:
wb.Close True
app.Close
The application object doesn't have a Close
method.
Not bugs, but things worth improving:
app.DisplayAlerts = False
should go before the loop starts unless you re-enable it inside the loop as well.
I'd recommend adding a line app.Visible = False
after you create the application object. When you have to debug your script you can simply change that value to True
to show the application on your desktop. That helps a lot with finding bugs.
Fixed-up script:
Set app = CreateObject("Excel.Application")
app.Visible = False
app.DisplayAlerts = False
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("Y:\Billing_Common\autoemail").Files
If LCase(fso.GetExtensionName(f)) = "xlsx" Then
Set wb = app.Workbooks.Open(f.Path)
wb.Save
wb.Close True
End if
Next
app.Quit
Set app = Nothing
Set fso = Nothing