Wednesday, December 23, 2015

Ms Excel macro to create txt file

Macro to create txt file (flat file). You could change separator as you need. 

Txt creator

Here is the code:

Sub CreateTXT()

    Dim rCell As Range
    Dim rRow As Range
    Dim sOutput As String
    Dim sFname As String, lFnum As Long
      
   
    'Open a text file to write


     sFname = "C:\AX\" & ActiveSheet.Name & ".txt"
    lFnum = FreeFile
       
    Open sFname For Output As lFnum
    'Loop through the rows'
        For Each rRow In ActiveSheet.UsedRange.Rows
        'Loop through the cells in the rows'
        For Each rCell In rRow.Cells
            sOutput = sOutput & rCell.Value & ";"  'SEPARATOR !!!
        Next rCell
         'remove the last comma'
        sOutput = Left(sOutput, Len(sOutput) - 1)
      
        'write to the file and reinitialize the variables'
        Print #lFnum, sOutput
        sOutput = ""
     Next rRow
  
    'Close the file'
    Close lFnum
       
   
End Sub







No comments:

Post a Comment