VBS對文本文件編輯只有使用FileSystemObject的OpenTextFile方法。然而OpenTextfile只有讀和寫還有追加的功能,並且每種功能只能單獨使用,太無語!oop
我便寫了個腳本。主要功能是實現對讀取每一行而後與關鍵字符串進行對比,最後在與關鍵字符串相符的行後面輸入本身想輸入的字符串行。post
代碼以下:對象
Option Explicitblog
Private Function SpecifyToWrite(FilePath,SearchString,IntoString)ip
Const ForReading=1,ForWriting=2ci
Dim fso,f,Msg字符串
Dim WriteString,ReadStringget
Set fso=CreateObject("Scripting.FileSystemObject") '建立FileSystemObject對象並賦值給fso博客
Set f=fso.OpenTextFile(Filepath,ForReading) '使用OpenTextfile的方法並賦值fit
'修改段 begin
Do Until f.AtEndOfStream '檢查是否是到文件末尾
ReadString=f.ReadLine ‘讀取一行
If Trim(ReadString)=SearchString Then '去掉讀取字符串
ReadString=ReadString+vbCrlf+IntoString
End If
WriteString=WriteString+ReadString+vbCrlf
Loop
'修改段 End
f.Close
Set f=Nothing
Set f=fso.OpenTextFile(FilePath,ForWriting)
f.Write(WriteString)
Msg=MsgBox ("ok")
End Function
Private Function Main()
Dim WriteFilePath
WriteFilePath="D:\軟件\testfile.txt"
Call SpecifyToWrite(WriteFilePath,"3","4")
End Function
Call Main()