Tjm92
Tjm92

Reputation: 317

Save each data row in a separate, new CSV

I've been struggling today with some VBA and have been looking on Stack for a solution to my problem, unfortunately I haven't had any luck whatsoever and so was wondering if somebody could help out. Would be extremely grateful for any assitance, I'm almost pulling my hair out right now. :)

Original Data

Example Final CSV Export, Filename: D29.csv

Upvotes: 0

Views: 902

Answers (1)

Variatus
Variatus

Reputation: 14373

Please try this code.

Sub RowsToCSV()
    ' Variatus @STO 06 Apr 2020

    Dim Sinw As Integer                     ' remember setting
    Dim Path As String
    Dim Fn As String                        ' file name
    Dim Ws As Worksheet                     ' for input
    Dim CapsRng As Range
    Dim Rng As Range
    Dim Cl As Long                          ' last column
    Dim Rl As Long                          ' last row
    Dim R As Long

    ' you can specify another open workbook
    Set Ws = ThisWorkbook.Worksheets("Data")
    ' you can specify another output path but it must exist
    Path = Environ("UserProfile") & "\Desktop\CSV Test files\"

    With Application
        Sinw = .SheetsInNewWorkbook
        .SheetsInNewWorkbook = 1
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .DisplayAlerts = False              ' over-write existing without warning
    End With

    With Ws
        Rl = .Cells(.Rows.Count, 1).End(xlUp).Row
        Cl = .Cells(1, .Columns.Count).End(xlToLeft).Column
        Set CapsRng = .Cells(1, 1).Resize(1, Cl)
        For R = 2 To Rl                     ' start in row 2
            Set Rng = Application.Union(CapsRng, .Cells(R, 1).Resize(1, Cl))
            ' modify the file name here:-
            Fn = Format(Date, "yymmdd ") & "Test " & _
                 Trim(.Cells(R, 1).Value) & ".csv"
            With Workbooks.Add
                Rng.Copy Destination:=.Sheets(1).Cells(1, 1)
                .SaveAs Path & Fn, xlCSV
                .Close SaveChanges:=False
            End With
        Next R
    End With

    With Application
        .SheetsInNewWorkbook = Sinw         ' return to original setting
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayAlerts = True
    End With
End Sub

Upvotes: 1

Related Questions