将多个csv文件批量转换为excel文件的快速方法

时间:2018-09-26 17:23:33

标签: excel excel-vba

我有一个包含.csv类型文件的文件夹,我需要将其更改为.xlsx类型文件。这是我下面的代码,我无法将文件夹中的文件转换为.xlsx,我已经运行了代码,但没有收到错误消息,该代码只是没有将任何csv文件转换为xlsx文件。如果有区别,我文件夹中的文件将使用大写CSV文件而不是小写CSV文件。 任何帮助是极大的赞赏!

Sub ConvertCSVToXlsx()

    Dim myfile As String
    Dim oldfname As String, newfname As String
    Dim workfile
    Dim folderName As String

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

'   Capture name of current file
    myfile = ActiveWorkbook.Name

'   Set folder name to work through
    folderName = "C:\Users\m\Desktop\CSVtoEXCEL\"

'   Loop through all CSV filres in folder
    workfile = Dir(folderName & "*.CSV")
    Do While workfile <> ""
'       Open CSV file
        Workbooks.Open Filename:=folderName & workfile
'       Capture name of old CSV file
        oldfname = ActiveWorkbook.FullName
'       Convert to XLSX
        newfname = folderName & Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & ".xlsx"
        ActiveWorkbook.SaveAs Filename:=newfname, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
        ActiveWorkbook.Close
'       Delete old CSV file
        Kill oldfname
        Windows(myfile).Activate
        workfile = Dir()
    Loop

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

这会做你想要的!

Sub CSVtoXLSB2()
Dim wb As Workbook
Dim CSVPath As String
Dim sProcessFile As String

CSVPath = "C:\your_path_here\"
sProcessFile = Dir(CSVPath & "*.csv")
Do Until sProcessFile = ""   ' Loop until no file found.
    Set wb = Application.Workbooks.Open(CSVPath & sProcessFile)
    wb.SaveAs CSVPath & Split(wb.Name, ".")(0) & ".xlsb", FileFormat _
        :=50, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
        CreateBackup:=False
    wb.Close
    sProcessFile = Dir()   ' Get next entry.
Loop
Set wb = Nothing
End Sub