如果您的文件相当小,您可以将其作为一个整体阅读并像这样处理它:
filename = "C:\path\to\your.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
txt = fso.OpenTextFile(filename).ReadAll
data = Split(txt, vbNewLine)
If UBound(data) >= 0 Then data(0) = data(0) & ",batch"
If UBound(data) >= 1 Then
batchval = Left(data(1), InStr(data(1), ",")-1)
data(1) = data(1) & "," & batchval
End If
For i = 2 To UBound(data)
data(i) = data(i) & "," & batchval
Next
fso.OpenTextFile(filename, 2).Write Join(data, vbNewLine)
但是,对于大文件,不建议使用这种方法,因为它可能会导致内存耗尽,从而导致您的计算机停止运行。如果您的文件很大,您最好逐行处理文件,将输出写入临时文件,并在完成后替换原始文件。
filename = "C:\path\to\your.txt"
tmpfilename = filename & ".tmp"
Set fso = CreateObject("Scripting.FileSystemObject")
inFile = fso.OpenTextFile(filename)
outFile = fso.OpenTextFile(tmpfilename, 2, True)
If Not inFile.AtEndOfStream Then outFile.WriteLine inFile.ReadLine & ",batch"
If Not inFile.AtEndOfStream Then
line = inFile.ReadLine
batchval = Left(line, InStr(line, ",")-1)
outFile.WriteLine line & "," & batchval
End If
Do Until inFile.AtEndOfStream
outFile.WriteLine inFile.ReadLine & "," & batchval
Loop
inFile.Close
outFile.Close
fso.DeleteFile filename, True
fso.MoveFile tmpfilename, filename