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: 7
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

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.

Forum statistics

Threads
1,223,881
Messages
6,175,161
Members
452,615
Latest member
bogeys2birdies

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