Samples of VBA code I'm using in my daily tasks.

Wednesday, March 10, 2010

Read Text File

Use VBA to read a text file line by line, the whole file, and one by one character.

Dim objSource
Dim strLine
Dim objFSO
Const ForReading = 1
Dim strFile As String
Dim strTempFile As String

strTextFile = "C:\MyFileName.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSource = objFSO.OpenTextFile(strTextFile, ForReading)

' Read file line by line
Do Until objSource.AtEndOfStream
strLine = objSource.ReadLine
'Processing data
Debug.Print strLine
Loop

' Read file in one big buffer
strTextBuffer = objSource.ReadAll
Debug.Print strTextBuffer

objSource.Close
Set objSource = Nothing
Set objFSO = Nothing

'----------------------------------------

'To read the file one by one character use this:
Dim MyChar
Open "C:\MyTextFile.txt" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
MyChar = Input(1, #1) ' Get one character.
Debug.Print MyChar ' Print to the Immediate window.
Loop
Close #1 ' Close file.

No comments:

Post a Comment