将 CSV 转换为 XLS 不适用于 Office 2003

Converting CSV to XLS doesn't work with Office 2003

在装有 MS Office 365 的 PC 中尝试 运行 下面提到的脚本时,它工作正常,但如果我尝试在 PC 中 运行 相同的脚本,它会给我一个错误安装了 MS Office 2003。

Windows script Host
Line 36
Char 17
Error SaveAs method of Workbook class failed
Code 800A03EC
Source Miscrosoft Office Excel

目标:每隔一分钟将指定文件夹中的所有 CSV 文件转换为 XLS。如上所述,它在安装了 office 365 的机器上工作正常,但如果我在安装了 Office 2003 的机器上 运行 它会出错。它们都是独立的机器。请帮我解决这个兼容性问题,这样我就可以在安装了 MS Office 2003 的机器上 运行 这个脚本。

Dim waittime: waittime = 1 * 60 * 1000
'Constants
Const xlOpenXMLWorkbook = 51             '(without macro's in 2007-2016, xlsx)
Const xlOpenXMLWorkbookMacroEnabled = 52 '(with or without macro's in 2007-2016, xlsm)
Const xlExcel12 = 50                     '(Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
Const xlExcel8 = 56

Do
    ' Extensions for old and new files
    strExcel = "xls"
    strCSV = "csv"

    ' Set up filesystem object for usage
    Set objFSO = CreateObject("Scripting.FileSystemObject")

   ' Access the folder to process
    Set objFolder = objFSO.GetFolder("C:\Users\User\Desktop\CSV to XL")

    ' Load Excel (hidden) for conversions
    Set objExcel = CreateObject("Excel.Application")
    objExcel.Visible = False
    objExcel.DisplayAlerts = False

    ' Process all files
    For Each objFile In objFolder.Files
        ' Get full path to file
        strPath = objFile.Path
        ' Only convert CSV files
        If LCase(objFSO.GetExtensionName(strPath)) = LCase(strCSV) Then
            ' Display to console each file being converted
            'WScript.Echo "Converting """ & strPath & """"
            ' Load CSV into Excel and save as native Excel file
            Set objWorkbook = objExcel.Workbooks.Open(strPath, False, True)
            objWorkbook.SaveAs Replace(strPath, strCSV, strExcel), xlOpenXMLWorkbook
            objWorkbook.Close False
            Set objWorkbook = Nothing
        End If
    Next

    WScript.Sleep (waittime)
Loop

xlFileFormat 枚举的 xlOpenXMLWorkbook 值将文件另存为打开的 XML 工作簿 自 Office 2007 起才受支持。现在,由于您想将其保存为 Excel 2003 文件格式,因此您应该为 使用适当的值,在这种情况下,将是 xlExcel8 .

这是 xlFileFormat 枚举的所有值的列表:

xlFileFormat enumeration (Excel).

因此,您需要做的是将 SaveAs 方法调用中的 xlOpenXMLWorkbook 替换为 xlExcel8:

objWorkbook.SaveAs outputFilePath, xlExcel8 

编辑:

如果您只安装了 Office 2003,xlExcel8 似乎不受支持,因此您需要改用 xlExcel9795。首先,在文件顶部添加此常量:

Const xlExcel9795 = 43

然后,您可以像这样将它传递给 SaveAs 方法:

objWorkbook.SaveAs outputFilePath, xlExcel9795