one condition, multiple events

我的梦境 提交于 2019-12-01 20:59:27

I think you are looking for Select Case True, an enhanced use of the Select Case switch:

age = inputbox("I was wondering how old you are.")

Select Case True
    ' first handle incorrect input
    Case (not IsNumeric(age))
        WshShell.SendKeys "You silly, you have to enter a number.{ENTER}"
    ' You can combine cases with a comma:
    Case (age<3), (age>120)
        WshShell.SendKeys "No, no. I don't think that is correct.{ENTER}"

    ' Now evaluate correct cases
    Case (age>24)
        WshShell.SendKeys "I see you are " & age - 24 & " years older than me.{ENTER}"
    Case (age<24)
        WshShell.SendKeys "I see you are " & 24 - age &" years younger than me.{ENTER}"
    Case (age=24)
        WshShell.SendKeys "Wow were the same age!{ENTER}"

    ' Alternatively you can use the Case Else to capture all rest cases
    Case Else
        ' But as all other cases handling the input this should never be reached for this snippet
        WshShell.SendKeys "Woah, how do you get here? The Universe Collapse Sequence is now initiated.{ENTER}"

End Select

I put in some extra cases to show you the power of this enhanced switch. In contrary to If a And b Then statements, the cases with comma's are shortcircuited.

Encapsulate the redundant code in a procedure or function. Also a different control structure might be better suited for the kind of check you're applying:

If age>24 Then
  TypeResponse "I see you are " & (age-24) & " years older than me."
ElseIf age<24 Then
  TypeResponse "I see you are " & (24-age) & " years younger than me."
ElseIf age=24 Then
  TypeResponse "Wow were the same age!"
End If

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