3

When running the script below I see Error Line 2 Char 1 Invalid procedure call or argument please can someone advise:

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
Steve
  • 75
  • 2
  • 13
  • To add some explanation to the answer below, `ForReading` and `ForWriting` don't have any special meaning in vbscript, so you're effectively just passing in uninitialized variables. The possible arguments for file open options are 1 (to read the file), 2 (to write to the file), and 8 (to append to the file). If you want to use words like `ForReading` then you need to define `ForReading` to equal `1`, as per the answer. – 404 May 22 '15 at 11:09

1 Answers1

3

Try like that :

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 = 

EDIT : In this case you should use VBScript regular expressions like this :

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
Hackoo
  • 18,337
  • 3
  • 40
  • 70
  • Is there a way to replace by line number? So Jim is not replaced by James in the whole text file: for example only replace Jim on lines 112 and 167 Thank you for the help above Hackoo – Steve May 22 '15 at 13:29
  • Or replace by line content: find specific word in that line as it is possible the line numbers will change as this is a live document – Steve May 22 '15 at 14:01
  • Check my last edit using VBScript regular expressions ;) – Hackoo May 22 '15 at 15:14