I have the following code, I want it to open my files which are saved as .xlsx and simply save them again with the same filename but this time as a .xls file so that they are compatible with Excel 2003
Set app = CreateObject("Excel.Application")
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)
app.DisplayAlerts = False
wb.SaveAs "*.xls*"
wb.Close SaveChanges=True
app.Close
app.Quit
End if
Set f = Nothing
Set fso = Nothing
Next
Two serious bugs:
Set fso = Nothing
should not be inside your loop: you'll needfso
for the duration of the program.Also, drop
app.Quit
from the loop; keep Excel open until the veryend.
Set f = Nothing
is unnecessary (although benign); let the loop pick the values for you.As Bathsheba already pointed out,
Set fso = Nothing
andapp.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):or
wb.Close SaveChanges=True
VBScript doesn't support named parameters (see here). If you want to call the
Close
method with theSaveChanges
parameter set toTrue
you have to do it like this: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 toTrue
to show the application on your desktop. That helps a lot with finding bugs.Fixed-up script: