2013-04-02 32 views
2

我想弄清楚如何使用.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 

回答

6

我認爲你正在尋找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 
+2

封裝是一個很好的建議,但你的代碼是越野車。因爲你使用'Select Case age'和'age> 24','age <24'和'age = 24',所以你正在評估'{integer} = {True | False}'總是導致'False',被執行。 – AutomatedChaos

+0

啊,當然。在這種情況下,「If..ElseIf..Else」會更適合。固定。 –

+0

這是我的結果:'age = inputbox(「Type age here。」,,「」) 如果年齡> 24然後 text =「我看到你了」&(24歲)&「比我年長。 「 ElseIf <24然後 text =「我看見你了」&(24歲)&「比我年輕」。 ElseIf age = 24 Then text =「哇是同齡人!」 End If msgbox text WScript.Sleep 1000 WshShell.SendKeys text&「{ENTER ENTER」「 –