There are a couple of inbuilt features in Excel to import data from text files
In this tutorial, I will show how to read text file line by line using VBA which can prove useful to cater some special conditions based on which you may want to import the data to Excel. In theory you need to follow the below steps
The above code will read the code line by line. You can insert you logic in between to process the line read. You can also download the sample code here.
In this tutorial, I will show how to read text file line by line using VBA which can prove useful to cater some special conditions based on which you may want to import the data to Excel. In theory you need to follow the below steps
- Open a file
- Assign a file number to it
- Read the file line by line
- Close the file. The will free the file so that other applications can use it.
As discussed in the previous tutorial here, a developer tab can be enabled in Excel which can then be used to do various tasks. On the same lines let me explain, how to write a Macro which will Open a text file and read the contents from it.
To begin with, go to "Developer" tab and click on "View Code". This will open a window where you can write some VBA code. Insert a new module to the workbook as show below:
Now copy and paste the below code into it
Sub ReadTextFile()
Dim sBuffer As String
Dim sFileName As String
Dim iFileNumber As Integer
'File Path
sFileName = "C:\temp\test.txt"
' Check if the file exists
If Len(Dir$(sFileName)) = 0 Then
MsgBox ("File does not Exist")
Exit Sub
End If
'Assign a number which is not used yet
iFileNumber = FreeFile()
'Open the file and assign the number allocated to it
Open sFileName For Input As iFileNumber
'Loop through the file line by line until
'end of file is reached
Do While Not EOF(iFileNumber)
Line Input #iFileNumber, sBuffer
'Insert you logic to read and filter data here
Loop
'Close the file
Close iFileNumber
End Sub
Dim sBuffer As String
Dim sFileName As String
Dim iFileNumber As Integer
'File Path
sFileName = "C:\temp\test.txt"
' Check if the file exists
If Len(Dir$(sFileName)) = 0 Then
MsgBox ("File does not Exist")
Exit Sub
End If
'Assign a number which is not used yet
iFileNumber = FreeFile()
'Open the file and assign the number allocated to it
Open sFileName For Input As iFileNumber
'Loop through the file line by line until
'end of file is reached
Do While Not EOF(iFileNumber)
Line Input #iFileNumber, sBuffer
'Insert you logic to read and filter data here
Loop
'Close the file
Close iFileNumber
End Sub
The above code will read the code line by line. You can insert you logic in between to process the line read. You can also download the sample code here.
0 comments:
Post a Comment