Macro to export sheets as CSV

howard

Well-known Member
Joined
Jun 26, 2006
Messages
6,563
Office Version
  1. 2021
Platform
  1. Windows
i have a workbook with several sheet. I need a macro to save each of these sheets from sheet 4 onwards as a CSV file . It must be saved with the respective sheet names in folder C:\my documents containing the current month and year for eg if sheets are ETYB, RREZ etc save as ETYB April 2022.csv, RREZ April 2022 etc


Your assistance is most appreciated
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
Try something like this (the file is automatically closed at the end, so as not to mess up the structure of the file you have):
VBA Code:
Sub CreateCSVFiles()

    Dim s As Long
    Dim myDir As String
    Dim fName As String
    
'   Save workbook before starting
    ActiveWorkbook.Save
    
'   Designate directory to save files to
    myDir = "C:\My Documents\"
    
'   Loop through all sheets starting with the 4th
    For s = 4 To Worksheets.Count
        Sheets(s).Activate
'       Build file name
        fName = Sheets(s).Name & Format(Date, " mmmm yyyy") & ".csv"
'       Save as CSV file
        ActiveWorkbook.SaveAs Filename:=myDir & fName, FileFormat:=xlCSV, CreateBackup:=False
    Next s
    
'   Close workbook without saving
    Application.DisplayAlerts = False
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
        
End Sub
 
Upvote 0
Solution
Won't the index of the sheet get messed up if you move them around? That is, 4 could become 1?
I was thinking of using the codename property, assuming Sheet4 is the code name.
 
Upvote 0
Thanks for your code Joe -it works perfectly
 
Upvote 0

Forum statistics

Threads
1,215,024
Messages
6,122,729
Members
449,093
Latest member
Mnur

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top