怎么限制编辑框只能输入数字?大家给点代码参考参考吧?
怎么限制编辑框只能输入数字?大家给点代码参考参考吧?
[解决办法]
Public Function InputNumeric(KeyAscii As Integer, txtItem As Object)
'txtItem对象输入框只能输入数字
'在txtiem对象的 keypress 事件中调用
On Error Resume Next
Select Case KeyAscii
Case Asc( "- ") '允许负数
' If txtItem.SelStart = 0 Then
' If Left(txtItem.Text, 1) = "- " Then
' KeyAscii = 0
' Beep
' End If
' Else
' KeyAscii = 0
' Beep
' End If
If Len(txtItem.Text) > = 1 Then
KeyAscii = 0
If MsgBox( "不允许在中间输入负号,确定需要输入负号?确定单击OK重新输入,否则单击‘取消’退出 ", vbOKCancel, "提示 ") = vbOK Then
txtItem.Text = " "
txtItem.SetFocus
' txtItem.SelStart = 0
' txtItem.SelLength = 1
End If
Beep
End If
Case 8
'无变化,退格键不屏蔽
Case Asc( " ") '32
If txtItem.SelLength = 0 Then
KeyAscii = 0
End If
Case Asc( ". ") '46 '允许小数点
If InStr(txtItem.Text, ". ") Then
KeyAscii = 0
End If
Case Is < Asc(0) '48
KeyAscii = 0
Case Is > Asc(9) '57
KeyAscii = 0
End Select
End Function
[解决办法]
Public Function OnlyIntegerKey(ByVal KeyAscii As Integer) As Integer
Select Case KeyAscii
Case vbKeySpace, vbKeyDown To vbKeyInser, vbKeyHelp, _
39, 58 To 64, vbKeyA To vbKeyZ, _
vbKeyPageUp To vbKeyUp, Is > 91
Case vbKeyReturn
OnlyIntegerKey = 0
SendKeys "{TAB} "
Case Else
OnlyIntegerKey = KeyAscii
End Select
End Function
Private Sub Text_KeyPress(KeyAscii As Integer)
KeyAscii=OnlyIntegerKey(keyascii)
End Sub
如果要小数点自已加上去就行了
[解决办法]
'我觉得下面较好,做了一些限制,比如不能输入两个或以上的减号。不能输入多个小数点,这些都是必须的。我特意把注释加上了,便于楼主理解。
-----------------------------
Private Sub MyText_KeyPress(KeyAscii As Integer)
'MsgBox KeyAscii
Dim str As String
'取出按键以前的字符
str = Trim(MyText.Text)
Select Case KeyAscii
'Case 8, 9, 13, &H30 To &H39
'0---9的ascii码是 48--57
'13----回车键
'8---- 退格键
Case 8, 13, 48 To 57
If KeyAscii = 9 Then
MsgBox " "
End If
KeyAscii = KeyAscii
Case 45 '负号[只充许字符的第一个字符是负号而且只能有一个负号]
If MyText.SelStart = 0 And InStr(1, str, "- ") = 0 Then
KeyAscii = KeyAscii
Else
KeyAscii = 0
End If
Case 46 '小数点处理[前面字符中没有小数点则可以输入]
'如果是空字符则可以输入小数点,即第一个字符可以以小数点开头
If str = " " Then
KeyAscii = KeyAscii
Else
'如果不空则要判断是否以前没有小数点,不存在小数点则可以录入小数点
If (IsNumeric(str) = True And InStr(1, str, ". ") = 0) Then
'此时要判断值为正还是为负,如果为负,则小数点必须在负号后面[负号前面是不能出现小数点的]
If Val(str) > = 0 Then
'如果是正数或0,则小数点可以点在任何地方
KeyAscii = KeyAscii
ElseIf MyText.SelStart > = 1 Then
KeyAscii = KeyAscii
Else
KeyAscii = 0
End If
Else
KeyAscii = 0
End If
End If
Case Else
KeyAscii = 0
End Select
End Sub