使用vbs复制并替换txt文件中的简单文本

时间:2015-05-22 09:41:56

标签: vbscript

运行下面的脚本时,我看到错误行2字符1无效的程序调用或参数请有人建议:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Jim ", "James ")

Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForWriting)
objFile.WriteLine strNewText
objFile.Close

1 个答案:

答案 0 :(得分:2)

尝试这样:

Option Explicit
Const ForReading = 1
Const ForWriting = 2
Dim objFSO,objFile,strText,strNewText
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Jim", "James")

Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForWriting)
objFile.WriteLine strNewText
objFile.Close
set objFSO = Nothing
set objFile = 

编辑:在这种情况下,你应该使用像这样的VBScript正则表达式:

Option Explicit
Const ForReading = 1
Const ForWriting = 2
Dim objFSO,objFile,strText,strNewText,objRegEx
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForReading)
strText = objFile.ReadAll
objFile.Close
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True   
objRegEx.IgnoreCase = True
objRegEx.Pattern = "jim"
strNewText = objRegEx.Replace(strText,"James")
Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForWriting)
objFile.WriteLine strNewText
objFile.Close
set objFSO = Nothing
set objFile = Nothing