打开一个Excel文件并保存为.XLS

我有下面的代码,我想打开我的文件保存为.xlsx,并简单地将它们保存为相同的文件名,但这次是一个.xls文件,以便它们与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 

正如Bathsheba已经指出的, Set fso = Nothingapp.Quit属于脚本的末尾(循环之外)。 但是还有一些bug。

  • wb.SaveAs "*.xls*"

    您不能将工作簿保存为通配符名称。 如果要将工作簿保存为当前名称,只需使用wb.Save 。 否则,你将不得不使用一个明确的名字(你也应该设置文件types):

     wb.SaveAs "new.xlsx", 51 

    要么

     wb.SaveAs "C:\path\to\new.xls", -4143 
  • wb.Close SaveChanges=True

    VBScript不支持命名参数(请参阅此处 )。 如果你想调用SaveChanges参数设置为TrueClose方法,你必须这样做:

     wb.Close True 
  • app.Close

    应用程序对象没有Close方法。

没有错误,但值得改进的东西:

  • app.DisplayAlerts = False应该在循环开始之前进行,除非在循环中重新启用它。

  • build议在创build应用程序对象后添加一行app.Visible = False 。 当您必须debugging脚本时,您可以简单地将该值更改为True以在桌面上显示该应用程序。 这对寻找错误很有帮助。

固定脚本:

 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 

两个严重的错误:

  • Set fso = Nothing不应该在你的循环内:你需要在程序的持续时间fso

  • 另外,从循环中删除app.Quit ; 保持Excel打开,直到非常
    结束。

Set f = Nothing必要(虽然是良性的); 让循环为你挑选值。

 Dim app, fso, file, fName, wb, dir dir = "d:\path\" Set app = CreateObject("Excel.Application") Set fso = CreateObject("Scripting.FileSystemObject") For Each file In fso.GetFolder(dir).Files If LCase(fso.GetExtensionName(file)) = "xlsx" Then fName = fso.GetBaseName(file) Set wb = app.Workbooks.Open(file) app.Application.Visible = False app.Application.DisplayAlerts = False app.ActiveWorkbook.SaveAs dir & fName & ".xls", 43 app.ActiveWorkbook.Close app.Application.DisplayAlerts = True app.Application.Quit End if Next Set fso = Nothing Set wb = Nothing Set app = Nothing wScript.Quit