Excel VBA将.csv转换为Excel文件

我有一个包含.csv文件,.xls文件和xlsx文件的文件夹.下面的代码是整个项目的一部分(当我删除下面的代码时,剩下的代码实现了我想要的).从某个地方(这里和互联网周围)编译了大量代码.我想要代码做的只是打开文件夹中的.csv文件,将它们转换为Excel文件,关闭文件,然后删除文件夹中的.csv文件.最终发生的代码是代码创建的一个或两个文件从文件夹中删除,我什么都没有留下.在此先感谢您的帮助.

Sub Test()
'
' Test Macro
'
'Set variables for the below loop
Dim MyFolder As String
Dim MyFile As String
Dim GetBook As String
Dim GetBook2 As String
Dim MyCSVFile As String
Dim KillFile As String
MyFolder = "REDACTED"
MyFile = Dir(MyFolder & "\*.xls")
MyCSVFile = Dir(MyFolder & "\*.csv")

'Open all of the .csv files in the folder and convert to .xls
Do While MyCSVFile <> ""
    Workbooks.Open Filename:=MyFolder & "\" & MyCSVFile
    GetBook = ActiveWorkbook.Name
    GetBook2 = Left(GetBook, Len(GetBook) - 4)
    ActiveSheet.Name = "Sheet1"
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=GetBook2, FileFormat:=56
    ActiveWorkbook.Close False
    Kill MyFolder & "\" & GetBook
Loop

End Sub

最佳答案 您没有调用
Dir function来获取下一个文件.

Sub Test()
    'Set variables for the below loop
    Dim myFolder As String
    Dim getBook As String
    Dim myCSVFile As String

    Application.DisplayAlerts = False

    myFolder = Environ("TEMP") & Chr(92) & "REDACTED"

    myCSVFile = Dir(myFolder & "\*.csv")

    Do While myCSVFile <> ""
        Workbooks.Open Filename:=myFolder & "\" & myCSVFile
        getBook = ActiveSheet.Name  '<~ Sheet1 of an opened CSV is the name of the CSV
        ActiveSheet.Name = "Sheet1"
        ActiveWorkbook.SaveAs Filename:=myFolder & Chr(92) & getBook, FileFormat:=56
        ActiveWorkbook.Close False
        Kill myFolder & Chr(92) & myCSVFile  '<~~ delete the CSV, not the workbook
        myCSVFile = Dir   '<~~ this is important to get the next file in the folder listing
    Loop

End Sub

打开的CSV中唯一的工作表是以CSV命名的(没有.CSV扩展名),因此可以在Workbook.SaveAs method中使用.我使用xlOpenXMLWorkbook作为SaveAs FileFormat类型.

点赞