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