VBA – 打开xls,xlsx文件,将工作表导出到csv

我使用了2个不同的代码集合来完成以下任务:

把所有的xls,xlsx文件放在一个指定的目录(通常是4个文件)中,然后导出工作表中的数据来分隔csv文件。

一组代码循环遍历目录并findxls文件; 这完美的作品。 另一组代码将当前打开的工作表导出并将其导出到csv,这个工作也完美无缺。 但是,当我试图转换一个文件,通过使用第一组代码循环,我得到的错误取决于我修改。

我认为我创造的对象不是正确的types,所以它们不能被循环,但我不知道如何创build正确的对象。

Sub select_rows() strPath = "C:\temp\xldev" Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.DisplayAlerts = False Set objFso = CreateObject("Scripting.FileSystemObject") Set objFolder = objFso.GetFolder(strPath) For Each objFile In objFolder.Files If (objFso.GetExtensionName(objFile.Path) = "xls" Or objFso.GetExtensionName(objFile.Path) = "xlsx") Then Set objWorkbook = objExcel.Workbooks.Open(objFile.Path, ReadOnly) ' Include your code to work with the Excel object here Dim WS As Excel.Worksheet Dim SaveToDirectory As String Dim CurrentWorkbook As String Dim CurrentFormat As Long ' CurrentWorkbook = objWorkbook ' CurrentFormat = objFile.FileFormat ' Store current details for the workbook SaveToDirectory = "C:\temp\" For Each WS In objWorkbook.Worksheets Sheets(WS.Name).Copy ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV ActiveWorkbook.Close savechanges:=False ThisWorkbook.Activate Next Application.DisplayAlerts = False objWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat Application.DisplayAlerts = True ' objWorkbook.Close True 'Save changes End If Next objExcel.Quit End Sub 

这可能是你的问题

使用VBScript将xls / xlsx文件(所有表)转换为csv

您正在使用Workbook对象来保存工作表。 尝试使用工作表对象。

尝试这个:

 Dim objExcel Dim objWorkBook Dim strPath Const xlCSV = 6 strPath = "C:\temp\filename" Set objExcel = CreateObject("EXCEL.APPLICATION") Set objWorkBook = objExcel.Workbooks.Open(FileName:=strPath & ".xlsx") On Error Resume Next objExcel.DisplayAlerts=False With objWorkbook .RefreshAll .Saveas FileName:=strPath & ".csv", FileFormat:=xlCSV, Local:=True .Close SaveChanges:=False objExcel.DisplayAlerts=True objExcel.Quit Set objWorkBook = Nothing Set objExcel = Nothing