vb脚本if语句

时间:2015-03-03 06:25:02

标签: if-statement vbscript

如果必须存在于文件中的单词,我想用VB编辑文件。 当执行这个文件时,我想如果条件为真,则除了所有文件内容都被删除之外什么都不做。

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)

strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"

If InStr(1, strText, strSearchFor) > 0 then
    'do nothing
else
    strNewText = Replace(strText,"this word must to delete","this word must to exist" )
End If
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
objFile.WriteLine strNewText
objFile.Close

1 个答案:

答案 0 :(得分:1)

当你的条件为真时,那个因为strNewText将为null。仍然用空strText替换strNewText。  将您的作品放在if()旁边。所以它会解决问题。

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)

strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"

    If InStr(1, strText, strSearchFor) > 0 then
        'do nothing
    else
        strNewText = Replace(strText,"this word must to delete","this word must to exist" )

        Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
        objFile.WriteLine strNewText
        objFile.Close
    End If