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 techguruplus telegram group Join Our WhatsApp Group techguruplus whatsapp group
Nazim Khan - Author Image

Nazim Khan (Author) 📞 +91 9536250020
[MBA in Finance]

Nazim Khan is an expert in Microsoft Excel. He teaches people how to use it better. He has been doing this for more than ten years. He is running this website (TechGuruPlus.com) and a YouTube channel called "Business Excel" since 2016. He shares useful tips from his own experiences to help others improve their Excel skills and careers.

Leave a Comment