If IsNumeric(Text1) = False Then Text1 = "" End If
或者在keypress事件中拦截数字键,将其改为ascii的0,就等于没有按一样
'在keypress事件中 Private Sub text1_KeyPress(KeyAscii As Integer) keyascii=notxt(keyascii)End Sub Public Function NoTxt(ByVal AsciiCode As Integer, ByVal Msg As String) As Integer '=========================================== '* 限制输入字符 * '* 返回数字 * '=========================================== Dim i As Integer Const MSG_CAPTION = "系统提示" Const MSG_NAME = "错误!" & vbCrLf & vbCrLf & "只能键入数字。" i = AsciiCode If Msg = "" Then Msg = MSG_CAPTION End If '8 退格键 '9 制表符 '10 换行符 '13 回车 '46 小数点If i = 8 Then NoTxt = AsciiCode: Exit Function If i = 9 Then NoTxt = AsciiCode: Exit Function If i = 10 Then NoTxt = AsciiCode: Exit Function If i = 13 Then NoTxt = AsciiCode: Exit Function If i = 46 Then NoTxt = AsciiCode: Exit FunctionIf i < 48 Or i > 57 Then MsgBox MSG_NAME, vbInformation, Msg NoTxt = 0 Else: NoTxt = i End IfEnd Function
根据数字的KeyAscii在keypress事件中决断!
如果你的程序是在完全输入完文本框之后再判断,我同意spirit00(精灵)的看法: if IsNumeric(text1.text)=False then text1.text="" end if
Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii < 58 And KeyAscii > 47 Then Text1.SelStart = Len(Text1.Text) Text1 = Text1.Text + Chr(8)
End If
End Sub
如果你的程序是在文本框输入之后进行判断的话,我同意楼上的意见,用IsNumeric 函数吧! IF IsNumeric(text1.text)=False then text1.text="" End if
补充一句,其实这个判断语句可以用在文本框的LostFocus以及KeyPress事件中!
private sub text1_keypress(keyascii as integer) if keyascii<48 or keyascii>57 then keyascii=0 endif end sub
应该是这样: Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii > 47 And KeyAscii < 58 Then KeyAscii = 0 End If End Sub
Text1 = ""
End If
Private Sub text1_KeyPress(KeyAscii As Integer)
keyascii=notxt(keyascii)End Sub
Public Function NoTxt(ByVal AsciiCode As Integer, ByVal Msg As String) As Integer
'===========================================
'* 限制输入字符 *
'* 返回数字 *
'===========================================
Dim i As Integer
Const MSG_CAPTION = "系统提示"
Const MSG_NAME = "错误!" & vbCrLf & vbCrLf & "只能键入数字。"
i = AsciiCode
If Msg = "" Then
Msg = MSG_CAPTION
End If
'8 退格键
'9 制表符
'10 换行符
'13 回车
'46 小数点If i = 8 Then NoTxt = AsciiCode: Exit Function
If i = 9 Then NoTxt = AsciiCode: Exit Function
If i = 10 Then NoTxt = AsciiCode: Exit Function
If i = 13 Then NoTxt = AsciiCode: Exit Function
If i = 46 Then NoTxt = AsciiCode: Exit FunctionIf i < 48 Or i > 57 Then
MsgBox MSG_NAME, vbInformation, Msg
NoTxt = 0
Else: NoTxt = i
End IfEnd Function
if IsNumeric(text1.text)=False then
text1.text=""
end if
If KeyAscii < 58 And KeyAscii > 47 Then
Text1.SelStart = Len(Text1.Text)
Text1 = Text1.Text + Chr(8)
End If
End Sub
IF IsNumeric(text1.text)=False then
text1.text=""
End if
if keyascii<48 or keyascii>57 then
keyascii=0
endif
end sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii > 47 And KeyAscii < 58 Then
KeyAscii = 0
End If
End Sub