一个条件,多个事件
Posted
技术标签:
【中文标题】一个条件,多个事件【英文标题】:one condition, multiple events 【发布时间】:2013-04-02 20:24:06 【问题描述】:我正在尝试弄清楚如何使用 .vbs 在一个条件下使多个事件发生。 (这里我尝试使用 case 语句。)是否有这样的命令,或者我必须为每一行重写命令? (这要在之前的代码行中激活,然后在记事本上输入。)
msgbox("I was woundering how old you are.")
age=inputbox("Type age here.",,"")
Select Case age
Case age>24
x=age-24
WshShell.SendKeys "I see you are "&x&" years older than me."
WshShell.SendKeys "ENTER"
Case age<24
x=24-age
WshShell.SendKeys "I see you are "&x&" years younger than me."
WshShell.SendKeys "ENTER"
Case age=24
WshShell.SendKeys "Wow were the same age!"
WshShell.SendKeys "ENTER "
End Select
【问题讨论】:
【参考方案1】:我认为您正在寻找Select Case True
,这是对Select Case
开关的增强使用:
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
我添加了一些额外的案例来向您展示这种增强型开关的强大功能。与If a And b Then
语句相反,逗号的大小写是短路的。
【讨论】:
【参考方案2】:将多余的代码封装在一个过程或函数中。此外,不同的控制结构可能更适合您应用的检查类型:
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
【讨论】:
封装是个好建议,但你的代码有问题。因为您使用Select Case age
和age>24
、age<24
和age=24
,所以您评估integer = True|False
总是导致False
,所以不会执行任何案例。
啊,当然。在这种情况下,If..ElseIf..Else
会更合适。固定。
这是我的结果:age=inputbox("Type age here.",,"") If age>24 Then text="I see you are " & (age-24) & " years older than me." ElseIf age<24 Then text="I see you are " & (24-age) & " years younger than me." ElseIf age=24 Then text="Wow were the same age!" End If msgbox text WScript.Sleep 1000 WshShell.SendKeys text & "ENTER"
结果是“这就是我要做的”或结果是“现在尝试这个但它不起作用”?以上是关于一个条件,多个事件的主要内容,如果未能解决你的问题,请参考以下文章