Private Sub Text1_Change(Index As Integer)
If Index = 4 And Not IsNumeric(Text1(Index)) Then
If Text1(Index).Text = "" Then Exit Sub
Text1(Index).Text = Mid(Text1(Index).Text, 1, Len(Text1(Index).Text) - 1)
'MsgBox "只允许输入数字!"
Text1(Index).SelStart = Len(Text1(Index).Text)
End If
End Sub
给你两个自定义函数:
Public Function CheckNum(KeyAscii As Integer) As Boolean
'---------控制数字字符输入--------------
CheckNum = False
If (KeyAscii < 48 Or KeyAscii > 57) And _
KeyAscii <> 46 And KeyAscii <> 8 Then KeyAscii = 0
CheckNum = True
End Function
Public Function IsNum(Text1 As TextBox) As Boolean
'-------判断是否为数字-----------
IsNum = False
If IsNumeric(Text1.Text) = False Then
SM "请输入正确的数字!", 0
Text1.SetFocus
Exit Function
End If
IsNum = True
End Function
第一个函数在KeyPress时件中调用(也可随意控制所要输入的字符,加入起ascii code即可),第二个函数在保存时进行数据验证(因为用户可能粘贴文本)
调用方式如:if not CheckNum(...) then exit sub
'限制输入字符
Function ValiText(KeyIn As Integer, ValidateString As String, Editable As Boolean) As Integer
Dim ValidateList As String
Dim KeyOut As Integer
If Editable = True Then
ValidateList = UCase(ValidateString) & Chr(8)
Else
ValidateList = UCase(ValidateString)
End If
If InStr(1, ValidateList, UCase(Chr(KeyIn)), 1) > 0 Then
KeyOut = KeyIn
Else
KeyOut = 0
Beep
End If
ValiText = KeyOut
End Function
'txtboxs事件
Private Sub txtFields_KeyPress(index As Integer, KeyAscii As Integer)
If KeyAscii = 13 And index <> 25 Then
SendKeys "{tab}"
KeyAscii = 0
End If
If index = 4 Then
KeyAscii = ValiText(KeyAscii, "0123456789", True)
End If
End Sub
保存数据时加入如下代码作为验证
'验证身份证号码
Dim strBirthday1 As String, strBirthday2 As String
Dim strSex1 As String, strSex2 As String
If Combo(2).Text = "男" Then
strSex2 = 1
Else
strSex2 = 0
End If
If txtFields(8).Text = "" Then
!公民身份证件编号 = txtFields(8).Text & ""
ElseIf Len(txtFields(8).Text) = 15 Or Len(txtFields(8).Text) = 18 Then
If strBirthday1 = strBirthday2 And strSex1 = strSex2 Then
!公民身份证件编号 = txtFields(8).Text & ""
Else
MsgBox "身份证件编号出错,请重新输入。", vbInformation
cErr = True
txtFields(8).Text = ""
txtFields(8).SetFocus
Exit Sub
End If
If strBirthday1 = strBirthday2 And strSex1 = strSex2 Then
!公民身份证件编号 = txtFields(8).Text & ""
Else
MsgBox "身份证件编号出错,请重新输入。", vbInformation
cErr = True
txtFields(8).Text = ""
txtFields(8).SetFocus
Exit Sub
End If
End If
Else
Dim msg As Integer
msg = MsgBox("身份证件编号出错,按确定强行保存,按取消重新输入。", vbOKCancel + vbQuestion, "错误...")
If msg = vbCancel Then
cErr = True
txtFields(8).Text = ""
txtFields(8).SetFocus
Exit Sub
Else
!公民身份证件编号 = txtFields(8).Text & ""
End If
Private Sub Txtkey_Change()
Dim hh As Long
On Error GoTo errorhandle
hh = CLng(TxtKey.Text)
Exit Sub
errorhandle:
If Len(TxtKey.Text) <> 0 Then
TxtKey.Text = Left(TxtKey.Text, Len(TxtKey.Text) - 1)
TxtKey.SelStart = Len(TxtKey.Text)
Else
TxtKey.Text = ""
End If
End Sub