Read a text file and store data in a variable

Share this post
FaceBook  Twitter  Mixx.mn     

To Read data from a text/ flat file , use following code:-

1) Create a File System Object

2) Open Text File

3) read Line by line data from text/ Flat file and store in a variable seperating by a line feed.

4) Close the File

5) Discard all variables.

 

''''''''''''
 'reading input file
Function readFile(sPath)
    Dim objFSO, objFile, sData

'1) Create a File System Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")

'2) Open Text File
    Set objFile = objFSO.openTextFile(sPath, 1)
    sData = ""

'3) read Line by line data from text/ Flat file and store in a variable seperating by a line feed.
    Do Until objFile.atEndOfStream
        sData = sData & objFile.readLine & vbCrLf
    Loop

'4) Close the File
    objFile.Close

5) Discard all variables.
    Set objFile = Nothing
    Set objFSO = Nothing
    readFile = sData
End Function