我来写一段
private sub Text1_Keypress(Keyascii as integer)
Dim strvalid As String
strvalid = "0123456789"
'上面的字符串就是你允许用户输入的字符,还可以加入"."和"-"
If (InStr(strvalid, Chr(KeyAscii)) <> 0) Then
KeyAscii = 0
'如果输入的字符在已定义的字符串中出现了,就屏蔽掉
End If
End sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii <> vbKeyBack And KeyAscii <> Asc("-") And KeyAscii <> Asc(".") Then
If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0
End If
End If
End Sub
我也提供三种
api方法
Option Explicit
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Const GWL_STYLE = (-16)
Private Const ES_NUMBER = &H2000&
NumbersOnly = SetWindowLong(tBox.hWnd, GWL_STYLE, DefaultStyle Or ES_NUMBER)
End Function
直接校验,考了小数点
Public Sub VerifyFloat(KeyAscii As Integer, ByVal sText As String)
If KeyAscii = 8 Or KeyAscii = 13 Or (KeyAscii > 47 And KeyAscii < 58) Then
Exit Sub
ElseIf KeyAscii = 46 Then
If Not IsNumeric("0" & sText & Chr(KeyAscii)) Then KeyAscii = 0
Else
KeyAscii = 0
End If
End Sub
正则表达式
Private Sub Text1_KeyPress(KeyAscii As Integer)
If Not (Chr(KeyAscii) Like "[0-9]") Then KeyAscii = 0
End Sub