这是涉及Microsoft脚本运行时库的一系列技巧中的最后一篇,涉及通过该库创建,打开,写入,读取和关闭文本文件。 目前,脚本库无法以二进制模式处理文件的打开和操作,因此我们将仅演示与文本文件有关的此功能。 该代码非常简单,而且注释很少,因此我不会给您带来不必要的细节。 该代码发布在下面,如有任何问题,请随时询问:
'******************************************************************
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
From: https://bytes.com/topic/access/insights/774457-microsoft-scripting-runtime-4-a