Pat*_*ard 3 vbscript text replace
我正在研究这段代码
Dim strFirm,soNumber,strValues,arrStr,strCitrix,NewText,text
strFirm = "Gray"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("cloud.csv",1,True)
Do while not objTextFile.AtEndOfStream
arrStr = Split(objTextFile.ReadLine, ",")
If arrStr(0) = strFirm Then
soNumber = arrStr(1)
Exit Do
End If
Loop
objTextFile.Close
strCitrix = soNumber + 1
MsgBox "Cloud Client " & strFirm & " is now using " & strCitrix & " Citrix licenses."
NewText = Replace(soNumber, soNumber, strCitrix)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("cloud.csv",2,True)
objTextFile.Writeline NewText
objTextFile.Close
Run Code Online (Sandbox Code Playgroud)
但是当我运行代码时,替换会清除我文件中的所有文本,除了我正在编写的数字.
我想要它做的是保留所有其他文本,只更改一个指定的变量.
例
Client1,5
Client2,7
Client3,12
Gray,6
Client4,9
Client5,17
Client6,8
Run Code Online (Sandbox Code Playgroud)
并在运行脚本后
Client1,5
Client2,7
Client3,12
Gray,7
Client4,9
Client5,17
Client6,8
Run Code Online (Sandbox Code Playgroud)
谁能指出我做错了什么?
预先感谢您的帮助.
您的输出文件只包含您要更改的数字,因为您只从文件中读取的文本中提取该数字:
soNumber = arrStr(1)
Run Code Online (Sandbox Code Playgroud)
将它递增一:
strCitrix = soNumber + 1
Run Code Online (Sandbox Code Playgroud)
用增加的数字替换soNumber
(仅包含数字)中的数字:
NewText = Replace(soNumber, soNumber, strCitrix)
Run Code Online (Sandbox Code Playgroud)
然后只将该新号码写回文件:
objTextFile.Writeline NewText
Run Code Online (Sandbox Code Playgroud)
要保留您希望保留的原始内容的那些部分,您还需要将它们写回文件,而不仅仅是修改后的内容.
如果你逐行阅读源文件(这在处理大文件时是一个好主意,因为它避免了内存耗尽),你应该将输出写入临时文件:
Set inFile = objFSO.OpenTextFile("cloud.csv")
Set outFile = objFSO.OpenTextFile("cloud.csv.tmp", 2, True)
Do while not objTextFile.AtEndOfStream
line = inFile.ReadLine
arrStr = Split(line, ",")
If arrStr(0) = strFirm Then
soNumber = CInt(arrStr(1))
outFile.WriteLine arrStr(0) & "," & (soNumber + 1)
Else
outFile.WriteLine line
End If
Loop
inFile.Close
outFile.Close
Run Code Online (Sandbox Code Playgroud)
然后用修改后的文件替换原始文件:
objFSO.DeleteFile "cloud.csv", True
objFSO.MoveFile "cloud.csv.tmp", "cloud.csv"
Run Code Online (Sandbox Code Playgroud)
但是,如果您的输入文件很小,则只需读取整个文件,处理它并使用修改后的内容覆盖该文件就更容易:
text = Split(objFSO.OpenTextFile("cloud.csv").ReadAll, vbNewLine)
For i = 0 To UBound(text)
If Len(text(i)) > 0 Then
arrStr = Split(text(i), ",")
If arrStr(0) = strFirm Then
soNumber = CInt(arrStr(1))
text(i) = arrStr(0) & "," & (soNumber + 1)
End If
End If
Next
objFSO.OpenTextFile("cloud.csv", 2, True).Write Join(text, vbNewLine)
Run Code Online (Sandbox Code Playgroud)
该Len(text(i)) > 0
检查是用于跳过空线(包括在该文件的末尾的后换行),因为空字符串被分成空数组,这将反过来使检查arrStr(0) = strFirm
失败,并index out of bounds
错误.