Excel VBA将.csv转换为Excel文件

我有一个文件夹有.csv文件,.xls文件和xlsx文件。 下面的代码是一个整体项目的一部分(当我删除下面的代码,剩下的代码实现了我想要的)。 大部分的代码是从某处(在这里和在互联网上)编译的。 我想要的代码是只打开该文件夹中的.csv文件,将其转换为Excel文件,closures文件,然后删除文件夹中的.csv文件。 代码的结果是代码创build的一个或两个文件都从文件夹中删除,而我什么都没有留下。 在此先感谢您的帮助。

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函数来获取下一个文件。

 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方法中使用 。 我已经使用xlOpenXMLWorkbook作为SaveAs FileFormattypes。