Need help adding multiple functions to one VBScript

Viewed 167

I have some code that I learnt from Stack Overflow that finds specific text in a .txt file and replaces it with different text. In the code below it looks for the number '14' and replaces it with '8'. I'm pretty sure I understand how this code works after reading around this forum, so thanks for that.

Where I'm stuck is I then want it to repeat the process looking for a different number and replacing it but I can't figure out how to add a second function into the same set of code. I'm assuming it needs an 'if' or a 'do' but I'm a total beginner. Happy to learn anything you have.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If InStr(strLine,"14")> 0 Then
        strLine = Replace(strLine,"14","8")
    End If 
    WScript.Echo strLine
Loop
1 Answers

When it comes to re-using code Function and Sub are your friend.

  • Function will allow to pass arguments and return a result.
  • Sub procedures allow to pass arguments.

In this case I would create a Sub to process the manipulated file and pass in the arguments it needs to manipulate it, as you have nothing to return.

Sub ReplaceValueInFile(file, search, replace)
    Set objFS = CreateObject("Scripting.FileSystemObject")
    strFile = file
    Set objFile = objFS.OpenTextFile(strFile)
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        If InStr(strLine, search)> 0 Then
            strLine = Replace(strLine, search, replace)
        End If 
        WScript.Echo strLine
    Loop
End Sub

You can then call the Sub in code using;

Call ReplaceValueInFile("C:\File.txt", "14", "8")

But now it’s reusable, you can change the input file, the search string and the replace string in the procedure arguments;

Call ReplaceValueInFile("C:\NewFile.txt", "20", "2")
Related