VBA - Save Data in Separate Files

luckee

New Member
Joined
Sep 23, 2022
Messages
25
Office Version
  1. 2016
Platform
  1. Windows
Hi, I have a spreadsheet sorted by column A. I want the macro to split and save everything as a separate CSV file for each month but only include the data from column B to D.

Thanks in advance!
 

Attachments

  • Capture.JPG
    Capture.JPG
    14.1 KB · Views: 8
VBA Code:
Option Explicit
Sub Create_Txt_File()

Dim mypath As String, myfile As String
Dim data As String
Dim r As Long

On Error Resume Next
mypath = "c:\test\"
Kill mypath & "*.csv" 'this will delete all that file type within that folder
On Error GoTo 0

For r = 2 To Cells(Rows.Count, "A").End(xlUp).Row
     data = Cells(r, "B") & "," & Cells(r, "C") & "," & Cells(r, "D")
   
     myfile = Cells(r, "A") & ".csv"
   
     If Dir(mypath & myfile) = "" Then 'file does not exist - write the header row
        Open mypath & myfile For Append As #1
        Print #1, [B1] & "," & [C1] & "," & [D1]
        Close #1
   
     End If
   
    Open mypath & myfile For Append As #1
    Print #1, data
    Close #1
Next r
 
End Sub
thanks!
 
Upvote 0

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December

Forum statistics

Threads
1,224,813
Messages
6,181,117
Members
453,021
Latest member
Justyna P

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