需要帮助将多个函数添加到一个 VBScript
Need help adding multiple functions to one VBScript
我有一些从 Stack Overflow 中学到的代码,可以在 .txt 文件中找到特定的文本并将其替换为不同的文本。在下面的代码中,它查找数字“14”并将其替换为“8”。我很确定我在阅读了这个论坛后理解了这段代码是如何工作的,所以谢谢你。
卡住的地方是我希望它重复该过程以查找不同的数字并替换它,但我不知道如何将第二个函数添加到同一组代码中。我假设它需要一个 'if' 或一个 'do' 但我是一个初学者。很高兴学习你拥有的任何东西。
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
说到重用代码,Function
和 Sub
是你的朋友。
Function
将允许传递参数和 return 结果。
Sub
程序允许传递参数。
在这种情况下,我会创建一个 Sub
来处理被操纵的文件并传入它需要操纵它的参数,因为你没有任何东西可以 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
然后您可以在代码中调用 Sub
;
Call ReplaceValueInFile("C:\File.txt", "14", "8")
但现在它可以重复使用,您可以在过程参数中更改输入文件、搜索字符串和替换字符串;
Call ReplaceValueInFile("C:\NewFile.txt", "20", "2")
我有一些从 Stack Overflow 中学到的代码,可以在 .txt 文件中找到特定的文本并将其替换为不同的文本。在下面的代码中,它查找数字“14”并将其替换为“8”。我很确定我在阅读了这个论坛后理解了这段代码是如何工作的,所以谢谢你。
卡住的地方是我希望它重复该过程以查找不同的数字并替换它,但我不知道如何将第二个函数添加到同一组代码中。我假设它需要一个 'if' 或一个 'do' 但我是一个初学者。很高兴学习你拥有的任何东西。
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
说到重用代码,Function
和 Sub
是你的朋友。
Function
将允许传递参数和 return 结果。Sub
程序允许传递参数。
在这种情况下,我会创建一个 Sub
来处理被操纵的文件并传入它需要操纵它的参数,因为你没有任何东西可以 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
然后您可以在代码中调用 Sub
;
Call ReplaceValueInFile("C:\File.txt", "14", "8")
但现在它可以重复使用,您可以在过程参数中更改输入文件、搜索字符串和替换字符串;
Call ReplaceValueInFile("C:\NewFile.txt", "20", "2")