Forum Discussion

LeandroCampacci's avatar
LeandroCampacci
Copper Contributor
Apr 13, 2021
Solved

VBA - export two ranges to a CSV file

Hi everyone! I have the following VBA code that saves a Excel range in a CSV file. But I need to increment this code so that I can insert, in the same CSV file, a second sheet with another Exce...
  • HansVogelaar's avatar
    HansVogelaar
    Apr 14, 2021

    LeandroCampacci 

    Like this:

     

    Sub saveRangeToCSV()
        Dim myCSVFileName As String
        Dim myWB As Workbook
        Dim tempWB As Workbook
        Dim ws As Worksheet
        Dim rngToSave As Range
        'Dim Sharepoint As String
        'Dim Usuario As String
        Dim Protocolo As String
    
        Set myWB = ActiveWorkbook ' or ThisWorkbook
        'Sharepoint = myWB.Sheets("Config").Range("D5").Text
        'Usuario = myWB.Sheets("Config").Range("L6").Text
        'Protocolo = myWB.Sheets("Config").Range("J6").Text
    
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
        On Error GoTo err
    
        ' First export
        Set tempWB = Workbooks.Add(xlWBATWorksheet)
        Set ws = tempWB.Worksheets(1)
        ws.Name = "Export A"
        Set rngToSave = myWB.Worksheets("Config").Range("J5:BB6")
        rngToSave.Copy
        ws.Range("A1").PasteSpecial xlPasteValues
        myCSVFileName = myWB.Path & "\" & "CSV-Exported-File-A-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
        With tempWB
            .SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
            .Close
        End With
    
        ' Second export
        Set tempWB = Workbooks.Add(xlWBATWorksheet)
        Set ws = tempWB.Worksheets(1)
        ws.Name = "Export B"
        Set rngToSave = myWB.Worksheets("Config").Range("D8:E20")
        rngToSave.Copy
        ws.Range("A1").PasteSpecial xlPasteValues
        myCSVFileName = myWB.Path & "\" & "CSV-Exported-File-B-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
        With tempWB
            .SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
            .Close
        End With
    
    err:
        Application.DisplayAlerts = True
        Application.ScreenUpdating = True
    End Sub

     

Resources