我要实现对接受输入的文本框进行实时监测,只能接受输入数值,如果输入的为空格或字母等任何非数值内容,则即时报错.应该如何实现?

解决方案 »

  1.   

    不用报错,只有让它无法输入就行了:Private Sub Text1_KeyPress(KeyAscii As Integer)    If ((KeyAscii < 48 Or KeyAscii > 75) And KeyAscii <> 8) Then KeyAscii = 0End Sub
      

  2.   

    Private Sub Text1_KeyPress(KeyAscii As Integer)    If ((KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 8) Then
            KeyAscii = 0
            MsgBox "只能输入数字!", 48
            Exit Sub
        End IfEnd Sub
      

  3.   

    Chen,周末快乐呀!  能不能详细的说一说你这段代码呢?
      

  4.   

    Private Sub Text1_KeyPress(KeyAscii As Integer)
        If Not (Chr(KeyAscii) Like "[0-9]") And KeyAscii <> 8 Then
            KeyAscii = 0
            MsgBox "只能输入数字!", vbExclamation
        End If
    End Sub
      

  5.   

    也可以写文本框的Change事件,判断所接受的字符是否是数字,如果不是就丢掉它
    Private Sub Text1_Change()
        If Not IsNumeric(Text1.Text) Then
            Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
        End If
    End Sub
      

  6.   

    Private Sub Text1_Change()
        If Not IsNumeric(Text1.Text) Then
            MsgBox "不是数字"
            Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
        End If
    End Sub
      

  7.   

      TextBox 的 KeyPress() 事件就是在 TextBox 接收到任意字符前触发(包括控制字符),由系统自动调用,并传放相应字符的 ASCII 码(就是那个 KeyAscii )。  如果在事件代码中把 KeyAscii 置0,相应于把输入字符‘吃掉’了。  刚才试了一下,用这个代码好一点:
    Private Sub Text1_KeyPress(KeyAscii As Integer)    If (KeyAscii >= 32) Then
            If (KeyAscii >= 48 Or KeyAscii <= 57) Then Exit Sub
        Else
            If (KeyAscii > 0) Then Exit Sub
        End If
        KeyAscii = 0
        MsgBox "只能输入数字!", 48End Sub