xls到csv自动化

时间:2016-07-19 14:51:56

标签: vbscript

我正在使用一个脚本来获取目录中的所有xls文件并将它们保存为CSV文件。我想尝试添加两个修改但不确定如何。

首先,我想选择保存目录,因为它目前只保存在workingdir中。

其次,我想在最后删除xls文件。我没关系,我会好的。

以下是我正在使用的代码:

WorkingDir = "C:\test\excel"
Extension = ".XLS"

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)
    If UCase(ext) = UCase(extension) Then
        'open excel
        FileName = Left(aFile,InStrRev(aFile,"."))
        Set objWorkbook = objExcel.Workbooks.Open(aFile)
        SaveName = FileName & "csv"
        objWorkbook.SaveAs SaveName, 23
        objWorkbook.Close 
    End If
Next

Set objWorkbook = Nothing
Set objExcel = Nothing
Set fso = Nothing
Set myFolder = Nothing
Set fileColl = Nothing

1 个答案:

答案 0 :(得分:0)

@ Wezel:请在下面找到我在下面更改的代码(我在REM之后更改的名称中对我所做的更改进行了评论)。存在的Filename变量已经包含整个路径,而您所犯的错误是尝试将新路径与旧路径连接起来并产生类似这样的值" C:\ test \ csv \ C:\测试\ EXCEL \ samplefile1.xls&#34 ;.所以它抛出了一条未找到路径的错误。除此之外,我还为您的第二个要求添加了一个代码。如果有效,请告诉我

`WorkingDir = "C:\Test\Excel"
savedir="C:\Test\"     REM changed 
Extension = ".xls"

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, 23
    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`