Excel VBA to generate TXT file


Option Explicit

Sub sbMakeTXT()
 ' https://stackoverflow.com/questions/77618965/excel-vba-export-the-data-from-selected-cells-in-to-txt-format
 Dim iRows, iColumns, iRow, iColumn As Long
 Dim sText As String
 Dim sFileName As String
 Dim sTXTLine As String
 Dim sTab As String
 Dim iFileNumber As String
 Dim rSelectedRange As Range
 Set rSelectedRange = Application.Selection
 iColumns = rSelectedRange.Columns.Count
 iRows = rSelectedRange.Rows.Count
 sTab = Chr(9)
 sTXTLine = ""
 sFileName = "C:\Users\david\Desktop\a.txt"
 iFileNumber = FreeFile
 Open sFileName For Output As iFileNumber
 For iRow = 1 To iRows
  For iColumn = 1 To iColumns
   ' Use the .Text in the Cell not .Value to deal with formula results
   sText = Cells(iRow, iColumn).Text
   ' Remove TABs in case they interfere with the file structure
   sText = Replace(sText, sTab, "")
   sTXTLine = sTXTLine & sTab & sText
  Next iColumn
  Print #iFileNumber, sTXTLine
  sTXTLine = ""
 Next iRow
 Close #iFileNumber
End Sub