[英]How to open all files in the folder (xls and csv format files) - VBA
[英]VBA - open xls, xlsx files, export worksheets to csv
我正在使用两套不同的代码集来完成以下任务:
将所有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
尝试这个:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.