VBA Code to Export Data to a CSV File in Excel

VBA Code:

Sub ExportToCSV()
    Dim rng As Range
    Dim filePath As String
    Dim cellData As String
    Dim fileNumber As Integer
    
    ' Set the range of cells to export to CSV
    Set rng = Range("A1:C10") ' Change the range as desired
    
    ' Set the file path for the CSV file
    filePath = "C:\Data\export.csv" ' Change the file path as desired
    
    ' Open the CSV file for writing
    fileNumber = FreeFile
    Open filePath For Output As fileNumber
    
    ' Loop through each row in the range
    For Each Row In rng.Rows
        ' Loop through each cell in the row
        For Each cell In Row.Cells
            ' Get the cell data and write it to the CSV file
            cellData = cell.Value
            Print #fileNumber, cellData;
        Next cell
        
        ' Move to the next line in the CSV file
        Print #fileNumber, ""
    Next Row
    
    ' Close the CSV file
    Close fileNumber
    
    ' Inform the user that the data has been exported
    MsgBox "Data exported to CSV file successfully."
End Sub

Check All VBA Codes

Join Our Telegram Group

Join the TechGuruPlus Telegram group

Join Our WhatsApp Group

Join the TechGuruPlus WhatsApp group
Nazim Khan, founder of TechGuruPlus.com

— Founder & Editor, TechGuruPlus.com
[MBA in Finance]

Nazim Khan has spent over ten years working with Excel, Tally and office documentation in accounts, finance and MIS roles. He has been running TechGuruPlus.com since 2016, where he publishes free editable templates for office work, and the YouTube channel Business Excel. He has trained more than 50,000 people online. Every template on this site is built and checked by him before it is published.

Contact  Â·  Excel Course

Leave a Comment