vb 脚本 if 语句

vb script if statement

如果文件中必须包含的单词不存在,我想使用 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

因为当您的条件为真时 strNewText 将为空。并仍然用你的空 strNewText 替换 strText。 将您的作品放在 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