VBA Code to Import Data from a Text File into Excel

In the below code, You need to replace “C:\Path\to\your\file.txt” with the actual file path of the text file you want to import. Make sure the file path is correct and accessible.

VBA Code:

' VBA Code to Import Data from a Text File into Excel

Sub ImportTextFile()
    Dim filePath As String
    Dim ws As Worksheet
    Dim textData As String
    Dim textLines() As String
    Dim rowData() As String
    Dim rowNum As Long
    Dim colNum As Long
    
    ' Set the file path of the text file to import
    filePath = "C:\Path\to\your\file.txt" ' Replace with the actual file path
    
    ' Set the worksheet to import the data into
    Set ws = ThisWorkbook.Worksheets("Sheet1") ' Replace with the name of your worksheet
    
    ' Read the text file data into a variable
    Open filePath For Input As #1
    textData = Input$(LOF(1), 1)
    Close #1
    
    ' Split the text into individual lines
    textLines = Split(textData, vbCrLf)
    
    ' Loop through the lines and import the data into the worksheet
    For rowNum = 1 To UBound(textLines) + 1
        rowData = Split(textLines(rowNum - 1), vbTab) ' Use the appropriate delimiter
        
        ' Write the data into the worksheet
        For colNum = 1 To UBound(rowData) + 1
            ws.Cells(rowNum, colNum).Value = rowData(colNum - 1)
        Next colNum
    Next rowNum
    
    ' Display a message
    MsgBox "Text file data has been imported."
End Sub


Check All VBA Codes

Join Our Telegram Group

Join the TechGuruPlus Telegram group

Join Our WhatsApp Group

Join the TechGuruPlus WhatsApp group
Nazim Khan, founder of TechGuruPlus.com

— Founder & Editor, TechGuruPlus.com
[MBA in Finance]

Nazim Khan has spent over ten years working with Excel, Tally and office documentation in accounts, finance and MIS roles. He has been running TechGuruPlus.com since 2016, where he publishes free editable templates for office work, and the YouTube channel Business Excel. He has trained more than 50,000 people online. Every template on this site is built and checked by him before it is published.

Contact  Â·  Excel Course

Leave a Comment