2015-10-18 20 views
2

這個腳本給我一個介於1和3之間的數字並輸入相應的字母(1 = a,2 = b,3 = c)。我之前完成了這個工作,它在字母意義上正確工作。 InputBox得到一個高於0的數字,這就是它應該允許腳本輸入的字母數,但是我的do while max > count並沒有將它停在最大值。只要繼續下去,直到我通過任務管理器禁用它。有沒有人看到這有什麼問題?有人可以請解釋我的VBScript錯誤

Set ws = CreateObject("Wscript.Shell") 

max = InputBox("Max number of characters (Numbers Only!)", "Enter Integer") 

If max = "" Then 
    Wscript.Quit 
ElseIf max < 0 Then 
    Wscript.Quit 
End If 

count = 0 
ws.Run "notepad.exe" 
Wscript.sleep 1000 

Do While max > count 

    count = count + 1 
    Randomize 
    rand = Int((3 - 1 + 1) * rnd + 1) 

    If rand = 1 Then 
     char = "a" 
    ElseIf rand = 2 Then 
     char = "b" 
    ElseIf rand = 3 Then 
     char = "c" 
    End If 

    Wscript.sleep 50 
    ws.Sendkeys char 

Loop 

Wscript.Quit 

回答

2

的問題是,你max變量包含的不是原始數值3字符串"3"。對於字符串值vs數字,VBScript的相對比較運算符(>,>,>=,<=)不像其他語言中那樣工作(並且它們不基於字符串的第一個字符的ASCII值)。

的解決辦法是使用CInt確保max是數字:

Dim max 
max = InputBox(...) 
If max = "" Then ... End If 
max = CInt(max) 

Do While max > count 
    ... 
Loop 

BTW,我會重新命名counti,以更好地傳達其語義含義。

+0

謝謝你現在正在按照希望工作。但是,你能澄清一下你的意思嗎?我比'count'好,它代表什麼? – TheGamerLord

+0

'i'通常用作計數器變量的名稱(通常用作數組索引或迭代器,這是個很好的巧合,這些名稱以'i'開始,而'i'也恰好是字母表中最細的字母)。 – Dai

+0

好的感謝澄清(和我不是一個沒有lifer跟蹤我的stackoverflow constanyly刷新我只是碰巧看到它時,我回來了它XD – TheGamerLord

1

Comparison Operators (VBScript) reference:讀表達式如何比較或什麼從比較的結果,根據下面的亞型:

如果一個表達式爲數字,而另一個是一個字符串,則 數值表達式小於字符串表達。

我會用下面的代碼片段:

max = InputBox("Max number of characters (Numbers Only!)", "Enter Integer") 

If Not Isnumeric(max) Then Wscript.Quit ''' affects `max = ""` as well 
max = CInt(max)       ''' convert `max` to a Variant of subtype Integer 
If max < 0 Then Wscript.Quit 

Randomize StatementRnd FunctionLooping Through Code爲好。也許

Randomize 
For count = 1 to max 
    ''' more code here based on `count` value and `rnd()` function 
Next 

可能會更好(隨機種子)和簡單(循環)超過

count=0 
Do While max > count 
    count = count + 1 
    Randomize 
    ''' more code here based on `count` value and `rnd()` function 
Loop 

最後,閱讀bypassing the errant keystrokes complaint

一個我聽說過有關使用最大的抱怨對於宏的方法SendKeys 是,如果窗口焦點以某種方式在腳本執行的中間 中發生變化,則鍵擊將被髮送到 任何窗口接收焦點。現在這樣做的危險在於,應用於另一個窗口時,打算用於一個窗口的按鍵可能會產生災難性的影響(如導致數據丟失的 )。