We
can read the content of a text file using FileSystemObject methods and properties. Below are the
various methods and properties used to extract data from file.
1. Creating an instance of filesystem object
Before
reading content from a file, we have to create instance of filesystemobject.
Set objFSO = CreateObject("Scripting.FileSystemObject")
2. Opening an existing file to read
Set objTxtFile = objFSO.OpenTextFile(FilePath,iomode)
Iomode can have following values:
0 – For
reading – opens the file for reading.
1 – For
Writing – opens the file for writing, does overwrite the existing content in
file.
8 –
For Appending – opens the file for appending, new content is appended at the
end of file.
3. ReadAll method
It stores all the content of a file in a variable as string.sContent
= objTxtFile.ReadAll
4. ReadLine method
It allows a script to read individual lines in a text
file.
sContent
= objTxtFile.Readline.
To
read through all lines, use a Do Loop that continues until the AtEndOfStream
property is True.
Below
code snippet shows how to read through each line.
i=0
Do Until
objTxtFile.AtEndOfStream
sContent
= objTxtFile.ReadLine
sDataArray(i)
= objTxtFile.ReadLine
MsgBox sContent
i = i+1
Loop
Content
of each line can be stored in an array also.
5. Read(chr)
The Read method allows you to read only a specified number of characters.
Stores
number of characters as defined in chr.
sContent = objTxtFile.Read(5)
6. Skip(chr)
This method skips the number of characters defined in chr from the
text file
skip(5)
7. SkipLine
This method skips line of data from the text file.
skipline
8. AtEndOfLine Property
Returns true if
the file pointer is positioned immediately before the end-of-line marker in a TextStream file.
Can be useful to find characters in a line or reading characters till end of
line.
Do While file.AtEndOfLine <> True
9. Line property
gives the current line number of the textStream.
objTxtFile.line
10. Column Property
Read-only
property that returns the column number of the current character position in a TextStream file.
objTxtFile.Column
11. OpenasTextStream Method
This method is used with getfile method to read from
file.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTxtFile = objFSO.getFile(FilePath)
var objts = objTxtFile.OpenAsTextStream(iomode)
No comments:
Post a Comment