2010-12-22 80 views

回答

5

在文本框文本Change事件中,檢查輸入的值是否是數字。如果它不是一個數字,則再次設置舊值。

Dim textval As String 
Dim numval As String 

Private Sub TextBox1_Change() 
    textval = TextBox1.Text 
    If IsNumeric(textval) Then 
    numval = textval 
    Else 
    TextBox1.Text = CStr(numval) 
    End If 
End Sub 
+0

你寧願使用驗證事件。 – pinichi 2010-12-22 04:31:01

+0

這取決於。如果您希望驗證在用戶離開文本框控件並嘗試將焦點設置爲其他內容時僅輸入了數字,則應該使用「驗證」事件。如果你走這條路線,那麼只有這樣纔會出現錯誤或通知。另一方面,如果使用`Change`事件,則會立即通知用戶輸入的非數字值無效。 – 2010-12-22 04:41:33

8

右鍵單擊控制框>組件>控制 - > Microsoft Masked Edit Control 6.0。
或隨普通文本框:

Private Sub Text1_Validate(Cancel As Boolean) 
Cancel = Not IsNumeric(Text1.Text) 

End Sub 
3

我讓API爲我做的。我將這個函數添加到一個.bas模塊,並將其調用到任何需要設置爲數字的編輯控件。

Option Explicit 

Private Const ES_NUMBER = &H2000& 
Private Const GWL_STYLE = (-16) 
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long 


'set an editbox to numeric only - return the previous 
'style on success or zero on error 
Public Function ForceNumeric(ByVal EditControlhWnd As Long) As Long 
    Dim lngCurStyle As Long 
    Dim lngReturn As Long 

    lngCurStyle = GetWindowLong(EditControlhWnd, GWL_STYLE) 
    If lngCurStyle <> 0 Then 
     lngReturn = SetWindowLong(EditControlhWnd, GWL_STYLE, lngCurStyle Or ES_NUMBER) 
    End If 

    ForceNumeric = lngReturn 

End Function 

要使用它調用TextBox句柄的函數。

Private Sub Form_Load() 
    Dim lngResult As Long 

    lngResult = ForceNumeric(Text1.hwnd) 

End Sub 
0

我通常使用此代碼:

Private Sub text1_KeyPress(KeyAscii As Integer) 
    If Not IsNumeric(text1.Text & Chr(KeyAscii)) And Not KeyAscii = 8 Then KeyAscii = 0 
End Sub 
0

以下可用於全數字:

Private Sub text1_KeyPress(KeyAscii As Integer) 
    If Not IsNumeric(text1.Text & Chr(KeyAscii)) And Not KeyAscii = 8 Then KeyAscii = 0 
    if (KeyAscii>=43) and (KeyAscii<=46) Then KeyAscii = 0 
    'it ignores '-', '+', '.' and ',' 
End Sub 
0

我通常使用此代碼:

Private Sub text1_KeyPress(KeyAscii As Integer) 
    If Not IsNumeric(Chr(KeyAscii)) And Not KeyAscii = 8 Then 
     KeyAscii = 0 
    End If 
End Sub 

希望這有助於。

0
If Len(Text2.Text) > 0 Then 
    If IsNumeric(Text2.Text) = False Then 
     Text2.SetFocus 
     CreateObject("WScript.Shell").SendKeys "{BACKSPACE}" 
    End If 
End If 
0

試試這個代碼:

Private Sub Text1_Change() 
    textval = Text1.Text 
    If IsNumeric(textval) Then 
     numval = textval 
    Else 
     Text1.Text = CStr(numval) 
    End If 
End Sub 
相關問題