Thursday, September 4, 2025

ExportToCSV

 Sub ExportToCSV()

    Dim ws As Worksheet

    Dim exportRange As Range

    Dim lastRow As Long

    Dim filePath As String


    ' Set the worksheet (change Sheet10 to your actual sheet name if needed)

    Set ws = ThisWorkbook.ActiveSheet


    ' Find the last row with data in column A

    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row


    ' Define the range to export (A1 to D[lastRow])

    Set exportRange = ws.Range("A1:D" & lastRow)


    ' Set the file path (you can change this to your desired location)

    filePath = Application.ThisWorkbook.Path & "\ExportedData.csv"


    ' Export the range to CSV

    Open filePath For Output As #1

    Dim r As Range, cell As Range


    For Each r In exportRange.Rows

        Dim line As String

        line = ""

        For Each cell In r.Cells

            line = line & cell.Text & vbTab

        Next cell

        ' Remove trailing tab

        If Len(line) > 0 Then line = Left(line, Len(line) - 1)

        Print #1, line

    Next r

    Close #1



    MsgBox "Data exported to CSV successfully!" & vbCrLf & filePath, vbInformation

End Sub