How do I properly configure conditional actions with user input in VBS with MsgBox?

二次信任 提交于 2019-12-06 14:39:40
Hackoo

Give this example a try:

Option Explicit
Dim Title,Question
Title = "user input in VBS with MsgBox"
Question = MsgBox("Proceeding will wipe the contents of your C: Drive. Proceed ?",vbYesNo+vbQuestion, Title)
If Question = vbYes Then
    MsgBox "We proceed wipping your C:\ drive",vbExclamation,Title
    'Call your sub here to continue proceeding your script
Else
    MsgBox "Canceling the operation !",vbCritical,Title
    Wscript.Quit()
End If

For more information about MsgBox Constants

Lankymart

While @Hackoo's answer is technically correct it doesn't answer the initial question, so I'll attempt to here.

The reason for the error

Microsoft VBScript compilation error: Expected 'End'

is due to the If statement spanning more then one line without an End If to finish the statement block, as in @Hackoo's example adding End If will correct this error.

If for whatever reason you wanted to keep the syntax condensed you weren't far away you had two options;

  1. Put the If statements all on one line

    Option Explicit
    Dim vbsmsg
    vbsmsg = MsgBox("Proceeding will wipe the contents of your C: Drive. Proceed?", vbYesNo + vbQuestion, "Format Drive C:")
    
    If vbsmsg = vbYes Then Call MsgBox("The contents of your C: Drive could not be successfully deleted.", vbExclamation, "Error Formatting Drive C: - System Error 5")
    If vbsmsg = vbNo Then Call MsgBox("Not all of the contents of your C: Drive were successfully deleted. Please try again.", vbCritical, "Error Formatting Drive C: - System Error 303")
    

    which can be a little ugly looking at sometimes hard to follow (but that's just my opinion).

  2. Use the Line Continuation Character (_) to allow a single statement to span multiple lines, in VBScript this is also known as a Statement Break.

    Option Explicit
    Dim vbsmsg
    vbsmsg = MsgBox("Proceeding will wipe the contents of your C: Drive. Proceed?", vbYesNo + vbQuestion, "Format Drive C:")
    
    If vbsmsg = vbYes Then _
        Call MsgBox("The contents of your C: Drive could not be successfully deleted.", vbExclamation, "Error Formatting Drive C: - System Error 5")
    If vbsmsg = vbNo Then _
        Call MsgBox("Not all of the contents of your C: Drive were successfully deleted. Please try again.", vbCritical, "Error Formatting Drive C: - System Error 303")
    

As already mentioned it goes without saying that you should endeavour to use the VBScript Named Constants in code wherever possible instead of hard coded numeric values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!