Sunday 15 January 2017

Excel VBA: How to Extract Data from Excel to Text File

In this post we are going to see how to export data from excel to text file using VBA.

Below is the VBA Code.

Sub ExceltoText()

'Declaring the variables
Dim FileName, sLine, Deliminator As String
Dim LastCol, LastRow, FileNumber As Integer

'Excel Location and File Name
FileName = Thisworkbook.path & "\ExceltoText.txt"

'Field Separator
Deliminator = "|"

'Identifying the Last Cell
LastCol = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
FileNumber = FreeFile

'Creating or Overwrighting a text file
Open FileName For Output As FileNumber

'Reading the data from Excel using For Loop
For i = 1 To LastRow
For j = 1 To LastCol

'Removing Deliminator if it is wrighting the last column
If j = LastCol Then
sLine = sLine & Cells(i, j).Value
Else
sLine = sLine & Cells(i, j).Value & Deliminator
End If
Next j

'Wrighting data into text file
Print #FileNumber, sLine
sLine = ""
Next i

'Closing the Text File
Close #FileNumber

'Generating message to display
MsgBox "Text file has been generated"

End Sub

See it in action.


11 comments:

  1. Is it possible to keep the text file open after it has been generated? Thanks

    ReplyDelete
  2. plz do another one with comma delimited. Thanks

    ReplyDelete
  3. Plz disregard my previous request as I have tried it with the comma and it worked perfectly.
    Thanks.

    ReplyDelete
  4. Thank you for the useful video, pl tell me how to insert "Tab" as the deliminator instead of the"|" used in this video

    ReplyDelete
  5. can i get the excel file for the same

    ReplyDelete
  6. Thank you for this working solution. Any idea how to do the same thing coding the text file un UTF-8 format (this is needed when I have accentuated characters, like é ö ü and so on..

    ReplyDelete
  7. can you help me, VBA code Import
    Thanks,

    ReplyDelete
  8. Hi, this code is exactly what I need. Just One question, if I have a lot of blank lines, is there a way to skip the blanks and only export the lines that aren't blank?

    Thx in advance!

    Kenny

    ReplyDelete