我正在尝试从文本文件中替换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
我无法弄清楚如何进行多次替换。该代码非常适合单个替换功能但不超过一个... plz help
答案 0 :(得分:7)
您需要针对之前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正则表达式。)