Tuesday, August 7, 2018

VB script to read and write file

1. To Read line by line in a given file



Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",1)
Dim strLine
do while not objFileToRead.AtEndOfStream
     strLine = objFileToRead.ReadLine()
     'Do something with the line
loop
objFileToRead.Close
Set objFileToRead = Nothing

This will read "listfile.txt' line by line. 
Inside the loop you can do something you need
Let's say you need to write this output to another file.

Let's break the logic to few lines to understanding purposes.

1. create file object and assign to variable.

Set filesys = CreateObject("Scripting.FileSystemObject")


2. Declare the output file path

strOutputFile1= "C:\out.txt"

3. Open a file in writable format (8) and get an object reference

Set objReport1 = filesys.OpenTextFile(strOutputFile1, 8, True)

4. Inside the loop, write the reader content from other object line by line

objReport1.WriteLine strLine

5. close all open streams and close references

objReport1.Close

set objReport1 = nothing

-------------------------------------------------------------------------

Below is the complete vb script to read content from a file and write to another file

2. Read content from a given file line by line and do something and write back to another file



Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\emailList.txt",1)

' to write
Set filesys = CreateObject("Scripting.FileSystemObject")
strOutputFile1= "C:\out.txt"
Set objReport1 = filesys.OpenTextFile(strOutputFile1, 8, True)

Dim strLine
do while not objFileToRead.AtEndOfStream
     strLine = objFileToRead.ReadLine()
     'Do something with the line
 
'MsgBox strLine
' write
objReport1.WriteLine strLine
loop
objFileToRead.Close
Set objFileToRead = Nothing

'closing all for write
objReport1.Close

set objReport1 = nothing

No comments:

Post a Comment