How to read a Text file through VBA code

Here this article help to know "How to read a Text file through VBA code" in MS Access.

This article explains with the help of example: -

Firstly create a form with 2 buttons and 1 Text boxes. When user click on "Read File" button then read a Text file line by line and show the content of file in the Text box. Fig: - 1.1 show the form

How to register and add reference of DLL through VBA code Fig-1.1

Fig-1.1

After click on "Read File" button all the content of the file show in the Text box. As shown in fig : -1.2

How to register and add reference of DLL through VBA code Fig-1.2

Fig-1.2

VBA Code:-

Private Sub Test_Click()
Dim strFilePathName As String
Dim strFile As String
Dim lngPos As Long
Dim blnEOF As Boolean
Dim strFileLine As String
strFilePathName = "Path of your text file\filename.txt"
strFile = QuickRead(strFilePathName) & vbNewLine
lngPos = 1
Do Until blnEOF
Call QRLineInput(strFile, lngPos, strFileLine, blnEOF)
Loop
End Sub


-------------This function reads a file into a string.----------------

Public Function QuickRead(FName As String) As String
Dim I As Integer
Dim res As String
Dim l As Long
I = FreeFile
l = FileLen(FName)
res = Space(l)
Open FName For Binary Access Read As #I
Get #I, , res
Close I
QuickRead = res
End Function


------------------This function works like the Line Input statement'--------------------

Public Sub QRLineInput( _
ByRef strFileData As String, _
ByRef lngFilePosition As Long, _
ByRef strOutputString, _
ByRef blnEOF As Boolean _
)
On Error GoTo LastLine
strOutputString = Mid$(strFileData, lngFilePosition, _
InStr(lngFilePosition, strFileData, vbNewLine) - lngFilePosition)
lngFilePosition = InStr(lngFilePosition, strFileData, vbNewLine) + 2
Debug.Print strOutputString
Me.txtdisplay = Me.txtdisplay & strOutputString & vbLf
Exit Sub
LastLine:
blnEOF = True
End Sub


DISCLAIMER

It is advised that the information provided in the article should not be used for any kind formal or production programming purposes as content of the article may not be complete or well tested. Access Guru will not be responsible for any kind of damage (monetary, time, personal or any other type) which may take place because of the usage of the content in the article.