2

我正在尝试从文本文件中替换 3 个文本。我试过这个 -

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Aron_", "Lori_")
strNewText1 = Replace(strText, "Aron", "Jason")   'Not working
strNewText2 = Replace(strText, "Sketa", "Skicia") 'Not working


Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForWriting)
objFile.WriteLine strNewText 
objFile.WriteLine strNewText1 'Not working
objFile.WriteLine strNewText2 'Not working


objFile.Close

我无法弄清楚如何进行多次替换。代码非常适合单个替换功能,但不超过一个......请帮助

4

1 回答 1

9

您需要调用Replace先前的结果Replace

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Aron_", "Lori_")
strNewText1 = Replace(strNewText, "Aron", "Jason")
strNewText2 = Replace(strNewText1, "Sketa", "Skicia")

Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForWriting)
objFile.WriteLine strNewText2 

objFile.Close


您实际上可以重用单个变量,而不是使用strNewText, strNewText1, strNewText2

strText = Replace(strText, "Aron_", "Lori_")
strText = Replace(strText, "Aron", "Jason")
strText = Replace(strText, "Sketa", "Skicia")

然后:

objFile.WriteLine strText


此外,您可能需要考虑使用正则表达式一次匹配多个值。(在 SO 上搜索VBScript 正则表达式VBA 正则表达式。)

于 2013-02-20T05:52:57.633 回答