Microsoft脚本运行时#4

这是涉及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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值