This is the last in a series of Tips involving the Microsoft Scripting Runtime Library and deals with creating, opening, writing to, reading from, and closing Text Files via this Library. At this time, the Scripting Library cannot deal with the opening and manipulation of Files in Binary Mode, so we will only demonstrate this functionality as it relates to Text Files. The code is fairly straightforward and sparsely commented, so I will not bore you with unnecessary details. The code is posted below, any questions, please feel free to ask them:
-
'******************************************************************
-
Dim fso As FileSystemObject, ts As TextStream, fil As File, txtFile
-
'Set fso = CreateObject(“Scripting.FileSystemObject”) OR
-
Set fso = New FileSystemObject
-
'******************************************************************
-
-
'Opening a Text File and Reading its contents
-
Set ts = fso.OpenTextFile("C:\Test\Test.TXT", ForReading, False, TristateUseDefault)
-
-
Debug.Print ts.ReadAll 'Reads entire File contents
-
Debug.Print ts.Read(500) 'Reads 500 characters
-
Debug.Print ts.ReadLine 'Reads 1 entire line
-
Do Until ts.AtEndOfStream 'Reads entire File line by line
-
Debug.Print ts.ReadLine
-
Loop
-
-
ts.Close
-
Set ts = Nothing
-
-
'******************************************************************
-
-
'3 Methods to create a Sequential Text File
-
Set ts = fso.CreateTextFile("C:\Test\TextFile1.txt", True)
-
-
Set ts = fso.OpenTextFile("C:\Test\Test.txt", ForWriting)
-
-
fso.CreateTextFile ("C:\Test\TestFile3.txt")
-
Set fil = fso.GetFile("C:\Test\TestFile3.txt")
-
Set ts = fil.OpenAsTextStream(ForWriting)
-
-
'******************************************************************
-
-
'How to Open a File, use the 3 Write Methods to add data to
-
'the File, then Close the File
-
-
Set txtFile = fso.CreateTextFile("C:\Test\TextFile.txt", True)
-
txtFile.Write ("This is just a test. ") 'Write a Line
-
-
'Write a Line with a NewLine character
-
txtFile.WriteLine ("Testing 1, 2, 3.")
-
txtFile.Write "Test for the NewLine character!"
-
-
'Write 3 NewLine characters to the File
-
txtFile.WriteBlankLines (3)
-
txtFile.Write "Just to see if we have 3 blank lines!"
-
txtFile.Close
-
-
Set txtFile = fso.CreateTextFile("C:\Test\TextFile.txt", True)
-
txtFile.Close 'Critical
-
-
'Write a Line
-
Set fil = fso.GetFile("C:\Test\Textfile.txt")
-
Set ts = fil.OpenAsTextStream(ForWriting) 'ForAppending, ForReading
-
ts.Write "Hello World"
-
ts.Close
-
-
'******************************************************************
-
-
'Opening a File for Reading
-
Set fil = fso.GetFile("C:\Test\Textfile.txt")
-
Set ts = fil.OpenAsTextStream(ForReading)
-
-
'Read the contents of the File
-
S = ts.ReadLine 'Reads 1st line into S
-
S = ts.Read(25) 'Reads 25 characters into S
-
S = ts.ReadAll 'Read entire file into S
-
MsgBox S
-
ts.Close
-