Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export a worksheet range to csv using excel-vba

Tags:

excel

vba

I am exporting from Excel to a CSV by macro using this to name the file specifically from data in the worksheet in cells in cells that will form no part of the CSV data, only the file name:

Private Sub CommandButton1_Click()
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
Dim FileName3 As String
Path = "T:\Richards Reports\MG Orders\"
FileName1 = Range("A1")
FileName2 = Range("O1")
FileName3 = Range("M1")
ActiveWorkbook.SaveAs FileName:=Path & FileName1 & "_" & FileName2 & "_" &       FileName3 & ".txt", FileFormat:=xlCSV
End Sub

However, I need to be able to limit the output to a specific range, for example cells I6 to I60, I am struggling to find a way of accomplishing this, any suggestions appreciated. TIA Duncan

like image 469
duncan297 Avatar asked Jan 02 '26 02:01

duncan297


1 Answers

Here is the code to save selected range to .csv

Sub saveSelection2csv()
Dim range2save As Range
Dim filename As Range
Dim dataRow As Range
Dim dataRowArr() As Variant

    Set filename = Worksheets("Arkusz1").Range("A1")

    Open ThisWorkbook.Path & "\" & filename.Value & ".csv" For Output As #1

    For Each dataRow In Selection.Rows
        dataRowArr = dataRow.Value
        dataRowArr = Application.Transpose(Application.Transpose(dataRowArr))
        Print #1, Join(dataRowArr, ",")
    Next

    Close #1
End Sub
like image 101
avb Avatar answered Jan 03 '26 16:01

avb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!