Friday, April 4, 2014

One click export from Excel to CSV

Many a times we want to modify and frequently export the content from Excel to CSV.

Here is a quick macro that anyone can use to export the data from Excel. 

The CSV file will be generated without any prompts. All the data on the current worksheet will be exported. The CSV will be generated in the directory where your excel file is placed. The name of the CSV combines the Excel File Name, the Worksheet Name and current date and time.

Here is the code:

Sub SaveAsCSV() 
    Dim fs As Object, a As Object, i As Integer, s As String, t As String, l As String, mn As String 
    Set fs = CreateObject("Scripting.FileSystemObject") 
    Set a = fs.CreateTextFile(Application.ActiveWorkbook.Path + "\" + Replace(ActiveWorkbook.Name, ".xlsm", "") + "_" + ActiveSheet.Name + "_" + Format(Now(), "yyyy-MM-dd-hh-mm-ss") + ".txt", True) 
      
    For r = 1 To Range("A65536").End(xlUp).Row 
        s = "" 
        c = 1 
        While Not IsEmpty(Cells(r, c)) 
            s = s & Cells(r, c) & "," 
            c = c + 1 
        Wend 
        a.writeline s 'write line 
    Next r 
    
End Sub


Hope this helps.

No comments:

Post a Comment