如何让文本框只接受数字,我写的代码如下,为什么不管输什么进去都显示输入的不是数字,不接爱?
Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode < 48 Or KeyCode > 57 Then
MsgBox "输入的不是数字,不接受!"
If Len(Text1.Text) > 0 Then
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
End If
Exit Sub
End IfEnd Sub

解决方案 »

  1.   

    换成写在 keypress 中
      

  2.   

    Private Sub Text1_KeyPress(KeyAscii As Integer)
        If KeyAscii <> 8 Then   '接受backspace 键,允许删除
            If KeyAscii < 48 Or KeyAscii > 57 Then
                KeyAscii = 0        '如果不是数字,取消输入
            End If
        End If
    End Sub
      

  3.   

    寒!还真不明白这种功能有什么意义,看你上面的代码的意思,不就是输入字母后再删除吗?既然要删除,还输入进入干嘛?浪费代码?如果要提示,加一个 msgbox 不就可以了。Private Sub Text1_KeyPress(KeyAscii As Integer)
        If KeyAscii <> 8 Then   '接受backspace 键,允许删除
            If KeyAscii < 48 Or KeyAscii > 57 Then
                'keyascii=0     '如果不允许输入字母,取消这句的注释;否则,可以输入字母            msgbox "不是数字!"
            End If
        End If
    End Sub
      

  4.   

    很简单呀
    Private Sub Text1_KeyPress(KeyAscii As Integer)
        If Not IsNumeric(Chr(KeyAscii)) Then MsgBox "你输入了非数字!"
    End Sub