vbaexcelcsvexport-to-csv

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet


There are a lot of questions here to create a macro to save a worksheet as a CSV file. All the answers use the SaveAs, like this one from SuperUser. They basically say to create a VBA function like this:

Sub SaveAsCSV()
    ActiveWorkbook.SaveAs FileFormat:=clCSV, CreateBackup:=False
End Sub

This is a great answer, but I want to do an export instead of Save As. When the SaveAs is executed it causes me two annoyances:

Is it possible to just export the current worksheet as a file, but to continue working in my original file?


Solution

  • Almost what I wanted @Ralph, but here is the best answer, because it solves some annoyances in your code:

    1. it exports the current sheet, instead of just the hardcoded sheet named "Sheet1";
    2. it exports to a file named as the current sheet
    3. it respects the locale separation char.
    4. You continue editing your xlsx file, instead of editing the exported CSV.

    To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.

    Option Explicit
    Sub ExportAsCSV()
     
        Dim MyFileName As String
        Dim CurrentWB As Workbook, TempWB As Workbook
         
        Set CurrentWB = ActiveWorkbook
        ActiveWorkbook.ActiveSheet.UsedRange.Copy
     
        Set TempWB = Application.Workbooks.Add(1)
        With TempWB.Sheets(1).Range("A1")
          .PasteSpecial xlPasteValues
          .PasteSpecial xlPasteFormats
        End With        
    
        Dim Change below to "- 4"  to become compatible with .xls files
        MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
         
        Application.DisplayAlerts = False
        TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
        TempWB.Close SaveChanges:=False
        Application.DisplayAlerts = True
    End Sub
    

    Note some characteristics of the code above:

    1. It works just if the current filename has 4 letters, like .xlsm. Wouldn't work in .xls excel old files. For file extensions of 3 chars, you must change the - 5 to - 4 when setting MyFileName in the code above.
    2. As a collateral effect, your clipboard will be substituted with current sheet contents.

    Edit: put Local:=True to save with my locale CSV delimiter.