2010年4月2日 星期五

只能輸入數字的寫法

以 vb 為例,在實作前必須將 textbox 的 IMEMode 設為 off,原因在中文輸入法時,其numpad(右邊的數字鍵盤),所接收到的 KeyCode 全為 229。

程式如下:
Private Sub txtNum_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim numArray As Variant

    numArray = Array(8, 17, 37, 39, 46, 67, 86, 110, 190)

    If 47 < KeyCode And KeyCode < 58 Then 'Numkey 0-9
        Exit Sub
    ElseIf 95 < KeyCode And KeyCode < 106 Then 'Numpad 0-9
        Exit Sub
    Else
        num = 0
        For i = 0 To UBound(numArray)
            If numArray(i) = KeyCode Then num = numArray(i)
        Next
        KeyCode = num
       
    End If
  
End Sub
說明:除了判斷0~9之外也加入判斷 backspace、delete、"."、左/右方向鍵、numpad 的 "."

沒有留言:

張貼留言