我使用了两组不同的代码来完成以下任务:
将所有xls,xlsx文件放在指定目录(通常是4个文件)中,并将其工作表中的数据导出为单独的csv文件。
一组代码循环遍历目录并查找xls文件;这很完美。另一组代码采用当前打开的工作表并将其导出到csv,这也很有效。但是当我尝试使用第一组代码转换正在循环的文件时,我会根据我修改的内容得到错误。
我认为我创建的对象不是正确的类型,所以它们无法循环,但我不知道如何创建正确的对象。
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
答案 0 :(得分:1)
这可能是你的问题
Convert xls / xlsx files (all sheets) to csv using VBScript
您正在使用Workbook对象来保存工作表。尝试使用Worksheet对象。