打开并使用vscript将xlsx保存为csv文件

时间:2016-07-21 16:17:53

标签: vbscript

我有这个脚本可以正常使用xls,但我想将它用于xlsx。我将扩展名更改为.xlsx并将obj.workbook链接修改为51。它没有执行开放操作,但我不确定我缺少什么。

WorkingDir = "C:\Test\Excel"
savedir="C:\Test\"      
Extension = ".xlsx"

Dim fso, myFolder, fileColl, aFile, FileName, SaveName
Dim objExcel, objWorkbook

Set fso = CreateObject("Scripting.FilesystemObject")
Set myFolder = fso.GetFolder(WorkingDir)
Set fileColl = myFolder.Files

Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = False
objExcel.DisplayAlerts = False

For Each aFile In fileColl
ext = Right(aFile.Name,4)
name= Left(aFile.Name,Len(aFile.Name)-3)         REM changed 
If UCase(ext) = UCase(extension) Then
'open excel
FileName = Left(aFile,InStrRev(aFile,"."))
Set objWorkbook = objExcel.Workbooks.Open(aFile)
SaveName = savedir & name & "csv"            REM changed 
objWorkbook.SaveAs SaveName,51
objWorkbook.Close 
End If
Next
Set objWorkbook = Nothing
Set objExcel = Nothing
Set myFolder = Nothing
Set fileColl = Nothing
fso.DeleteFile(WorkingDir&"\*"&Extension) REM changed
Set fso = Nothing

2 个答案:

答案 0 :(得分:0)

你需要付出“自己动手”的代价。文件规范解析:

>> Extension = ".xlsx"
>> WScript.Echo Len(Extension)
>> ext = Right("a.xlsx", 4)
>> WScript.Echo Len(ext)
>> WScript.Echo CStr(UCase(ext) = UCase(extension))
>>
5
4
False
>>

查看这些FileSystemObject方法:

>> sFSpec = "C:\Some\Where\whaterver.xlsx"
>> WScript.Echo goFS.GetParentFolderName(sFSpec)
>> WScript.Echo goFS.GetBaseName(sFSpec)
>> WScript.Echo goFS.GetExtensionName(sFSpec)
>>
C:\Some\Where
whaterver
xlsx
>>

答案 1 :(得分:0)

@ Wezel:将以下行作为通用行,并且当长度发生变化时,扩展名发生变化时会导致问题

旧代码

ext = Right(aFile.Name,4)
name= Left(aFile.Name,Len(aFile.Name)-3)

修订代码

ext = Right(aFile.Name,Len(Extension))
name= Left(aFile.Name,Len(aFile.Name)-Len(Extension)) 

让代码与下面的代码一样通用,因此它适用于所有情况,只需根据需要改变前四行

修改后的代码

WorkingDir = "C:\Test\Excel"
savedir="C:\Test\"      
Extension = ".xlsx"
neededextension= ".csv"
Dim fso, myFolder, fileColl, aFile, FileName, SaveName
Dim objExcel, objWorkbook

Set fso = CreateObject("Scripting.FilesystemObject")
Set myFolder = fso.GetFolder(WorkingDir)
Set fileColl = myFolder.Files

Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = False
objExcel.DisplayAlerts = False

For Each aFile In fileColl
ext = Right(aFile.Name,Len(Extension))      REM changed
name= Left(aFile.Name,Len(aFile.Name)-Len(Extension))         REM changed

If UCase(ext) = UCase(extension) Then
'open excel
FileName = Left(aFile,InStrRev(aFile,"."))
Set objWorkbook = objExcel.Workbooks.Open(aFile)
SaveName = savedir & name & neededextension            REM changed 
objWorkbook.SaveAs SaveName,51
objWorkbook.Close 
End If
Next
Set objWorkbook = Nothing
Set objExcel = Nothing
Set myFolder = Nothing
Set fileColl = Nothing
fso.DeleteFile(WorkingDir&"\*"&Extension) REM changed
Set fso = Nothing

请告诉我这是否适合你需要的通用