2013-02-20 73 views
2

我想从一个文本file.I尝试这个 -使用VBScript

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 

我不能够想出如何做多replacement.The代码替换3文本替换在文本文件中的多个文本单工作完美替换功能,但不超过一个... plz帮助

回答

6

你需要调用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, strNewText1strNewText2

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

及更高版本:

objFile.WriteLine strText 


此外,您可能要考虑使用正则表达式同时匹配多个值。 (搜寻上SO为 VBScript的正则表达式VBA正则表达式

+0

我试图 - strNewText =替换(strText中, “Aron_”, “Lori_”) strNewText1 = REPLACE(strNewText, “阿隆”,“杰森“)。但它不工作.. – Praveenks 2013-02-20 06:02:54

+0

什么不工作?您是否收到错误,或者文件没有​​被写入,或者文件的文本没有被更改? – 2013-02-20 06:08:05

+0

只适用于第一个替换正在写入文件和文本正在改变,但第二次替换文本没有得到改变.. – Praveenks 2013-02-20 06:20:41