Do you need to write an Excel data table to the text file using excel VBA? This article will show you step by step how to use VBA to write data to a text file from your workbooks.
You may be asked to export your excel data table to a text file with a delimiter such as (Comma, Semicolon, Tab, Special characters, etc)
Suppose you have the below data Sales Table in your excel file and need to export it to a text file.
Country Sales Table in Excel File: 3 Fields [ Country, Sales, Profit ] and 10 Records (incl. header)
![VBA to write data to a Text file - input excel table](https://i0.wp.com/pptexcel.com/wp-content/uploads/2022/10/a005_001.png?resize=344%2C224&ssl=1)
VBA script will create a text file salesTable.txt and your final output looks like the below image.
![VBA to write data to a Text file - output file](https://i0.wp.com/pptexcel.com/wp-content/uploads/2022/10/a005_002.png?resize=275%2C284&ssl=1)
VBA Script
![variable declaration](https://i0.wp.com/pptexcel.com/wp-content/uploads/2022/10/a005_003.png?resize=359%2C158&ssl=1)
![VBA Script to export data](https://i0.wp.com/pptexcel.com/wp-content/uploads/2022/10/a005_004.png?resize=715%2C533&ssl=1)
Sub ExportData()
'Delcare Variables
Dim fileName As String, rg As Range, cVal As Variant, rowNo As Integer, colNo As Integer
'Path for your text file
fileName = "D:\Projects\xl\pptExcel\WriteTextFile\salesTable.txt"
'Data table need to export on text file
Set rg = ActiveSheet.Range("A1:C11")
Open fileName For Output As #1
'Loop to iterate both rows and columns
'No of Rows
For rowNo = 1 To rg.Rows.Count
'No of Columns
For colNo = 1 To rg.Columns.Count
cVal = rg.Cells(rowNo, colNo).Value
'current value on text file
If colNo = rg.Columns.Count Then
Write #1, cVal 'write only text for last record
Else
Write #1, cVal, 'write text with comma
End If
Next colNo
Next rowNo
'Close your data file
Close #1
End Sub
Copy the above VBA Script and Paste it into your VBA module
If you need to use any other delimiters instead of commas, you can update the below line of code.
Write #1, cVal, 'write text with comma
Please follow the below steps to assign the above macro to your worksheet button
![](https://i0.wp.com/pptexcel.com/wp-content/uploads/2022/10/a005_005.png?resize=241%2C193&ssl=1)
- Add a shape Export Data to your worksheet.
![Assign macro to a worksheet button in excel](https://i0.wp.com/pptexcel.com/wp-content/uploads/2022/10/a005_006.png?resize=360%2C539&ssl=1)
- Right-click on the Export Data button and choose Assign Macro…
- Select ExportData Macro from the list of macros in the Assign Macro dialog box
- Save your excel file as Excel Macro-Enabled Workbook *.xlsm
- Click the button Export Data
Conclusion
Reading and writing a text file is a basic operation for data analysis. In excel you can simply open your excel file copy the data table and paste it into your text file manually. You can use VBA Script If you need to automate the process to write data from your excel file.