打开一个Excel文件并另存为.XLS格式。

6
我有以下代码,我希望它可以打开我的文件,这些文件保存为 .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
3个回答

13

正如Bathsheba已经指出的那样,Set fso = Nothingapp.Quit应该放在脚本的末尾(循环体外)。然而,还有一些bug。

  • wb.SaveAs "*.xls*"

    你不能将工作簿保存为通配符名称。如果要将工作簿保存在其当前名称下,只需使用wb.Save即可。否则,您必须使用明确的名称(您还应该设置文件类型):

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

    VBScript不支持命名参数(参见这里)。如果您想使用SaveChanges参数设置为True调用Close方法,您需要像这样操作:

  • wb.Close True
    
  • app.Close

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

  • 不是错误,但值得改进的事项:

    • app.DisplayAlerts = False 应该在循环开始之前设置,除非你在循环内也重新启用它。

    • 我建议在创建应用程序对象后添加一行app.Visible = False。当你需要调试脚本时,可以简单地将该值更改为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
    

    能否将它保存为新的文件类型,但保留原始名称?我正在使用您提供的脚本。顺便说一句,非常感谢! - Nathan Hawthorne
    这是可能的,但这样做可能会遇到问题(例如,您可以将OpenXML工作簿保存为旧的工作簿格式,但尝试在Excel中打开该文件将导致错误)。 - Ansgar Wiechers
    2
    稍作修改即可将此脚本转换为从 xlsxbxlsxm 的转换器:http://pastebin.com/JJbM9qRC - Adriano P
    1
    @AnsgarWiechers,保存为行中的数字是什么意思? - STF
    1
    @EsterF。它们是文件格式参数的数字值。请查看文档 - Ansgar Wiechers

    5

    两个严重的错误:

    • Set fso = Nothing 不应该在循环内部:您需要 fso 在程序的整个过程中都可用。

    • 同时,从循环中删除 app.Quit; 保持 Excel 打开直到程序结束。

    Set f = Nothing 是不必要的(虽然无害); 让循环为您选择值即可。


    3
    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
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接