• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1947
  • Last Modified:

Excel VBA export to tab delimited text file

I want to export a sheet data using vba code to tab delimited text file.
The data is like this.
I do not want to use "save as" because then active file will be .txt
Can you help me?
Rajesh Joshi
Rajesh Joshi
1 Solution
MichaelBusiness AnalystCommented:
Try this code by Chip Pearson.

It creates a new text file, so it doesn't affect your active excel file.

Copy the code to a module in the workbook you want to export. Modify your file path in the 'DoTheExport()' sub and execute it.

Sub DoTheExport() 
    ExportToTextFile FName:="C:\Test.txt", Sep:="vbTab", _
       SelectionOnly:=False, AppendData:=True
End Sub

Public Sub ExportToTextFile(FName As String, _
    Sep As String, SelectionOnly As Boolean, _
    AppendData As Boolean)

Dim WholeLine As String
Dim FNum As Integer
Dim RowNdx As Long
Dim ColNdx As Integer
Dim StartRow As Long
Dim EndRow As Long
Dim StartCol As Integer
Dim EndCol As Integer
Dim CellValue As String

Application.ScreenUpdating = False
On Error GoTo EndMacro:
FNum = FreeFile

If SelectionOnly = True Then
    With Selection
        StartRow = .Cells(1).Row
        StartCol = .Cells(1).Column
        EndRow = .Cells(.Cells.Count).Row
        EndCol = .Cells(.Cells.Count).Column
    End With
    With ActiveSheet.UsedRange
        StartRow = .Cells(1).Row
        StartCol = .Cells(1).Column
        EndRow = .Cells(.Cells.Count).Row
        EndCol = .Cells(.Cells.Count).Column
    End With
End If

If AppendData = True Then
    Open FName For Append Access Write As #FNum
    Open FName For Output Access Write As #FNum
End If

For RowNdx = StartRow To EndRow
    WholeLine = ""
    For ColNdx = StartCol To EndCol
        If Cells(RowNdx, ColNdx).Value = "" Then
            CellValue = Chr(34) & Chr(34)
           CellValue = Cells(RowNdx, ColNdx).Value
        End If
        WholeLine = WholeLine & CellValue & Sep
    Next ColNdx
    WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))
    Print #FNum, WholeLine
Next RowNdx

On Error GoTo 0
Application.ScreenUpdating = True
Close #FNum

End Sub

Open in new window


Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now