有关VB中TextBox控件的问题

来源:百度知道 编辑:UC知道 时间:2024/05/21 18:40:17
要求:控制TextBox控件,使得输入的字符只能为数字。
满足该要求的代码应该怎么写?

Private Sub Text1_Change(Index As Integer)
if text1.text<>"" then
if ltrim(str(val(text1.text)))<>text1.text then text1.text=""
end if
End Sub

改进2楼的代码:
Private Sub Text2_KeyPress(KeyAscii As Integer)
Const xStr As String = "0123456789.-"
If KeyAscii = 46 And InStr(Text2, ".") > 0 Then KeyAscii = 0 '只能输入一个小数点
If KeyAscii = 45 And Len(Text2) > 0 Then KeyAscii = 0 '只能在最前面输入-号
If KeyAscii = 8 Then Exit Sub '退格键不受限制
KeyAscii = IIf(InStr(xStr, Chr(KeyAscii)), KeyAscii, 0) '只能输入规定的字符

End Sub

Private Sub textbox1_KeyPress(KeyAscii As Integer)
If KeyAscii <> vbKeyBack And KeyAscii < 48 Or KeyAscii > 57 And KeyAscii <> 13 Then
KeyAscii = 0
End If