2013-02-20 76 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