Excel VBA to convert CSV to Excel file

I have a folder with .csv files, .xls and xlsx files. The code below is part of the overall project (when I delete the code below, the remaining code reaches what I want). Most of the code has been compiled somewhere (here and around the Internet). I want the code to work only with open .csv files in a folder, convert them to an Excel file, close files and delete .csv files in a folder. What ultimately happens with the code is that one or both of the files created by the code are deleted from the folder, and there is nothing left for me. Thanks in advance for any help.

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
+4
source share
1 answer

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.

+2

Source: https://habr.com/ru/post/1605609/


All Articles