学生系统中的输入文本内容,几乎都会涉及到字符限制问题,需要结合我们的现实生活进行相应的调整。字符限制的类型有多种,将学生系统中遇到的字符限制总结如下,把它们归结到一起,也会方便我们日后的使用。
1、去文本框空格(即当单击text就会有空格存在):
Private Sub txt?_Click()
Dim s As String
s = txtName.Text
s = Replace(s, " ", "")
txtName.Text = s
End Sub
2、只能输入汉字:
Private Sub txt?_KeyPress(KeyAscii As Integer)
If KeyAscii < 0 or KeyAscii =13 or KeyAscii = 8 Then Exit Sub
KeyAscii = 0
End Sub
3、限制特殊字符:
A
Private Sub txt?_KeyPress(KeyAscii As Integer)
If ((KeyAscii >= 48 And KeyAscii <= 57) Or (KeyAscii >= 65 And KeyAscii <= 90) Or _
(KeyAscii >= 97 And KeyAscii <= 122) Or (KeyAscii = 8)) = flase Then KeyAscii = 0
End Sub
B
Private Sub txt?_KeyPress(KeyAscii As Integer)
Dim cTemp As String
cTemp = "`~!@#$%^&*()-=_+[]{};:'|<>/?.‘“”’、,。——+()《》?,~·……¥!:;【】" & """ '禁止输入特殊的字符"
If InStr(1, cTemp, Chr(KeyAscii)) <> 0 Then KeyAscii = 0
End Sub
4、只能输入字母和汉字:
Private Sub txt?_KeyPress(KeyAscii As Integer)
If KeyAscii < 0 Or KeyAscii = 8 Or KeyAscii = 13 Then
ElseIf Not Chr(KeyAscii) Like "[a-zA-Z]" Then
KeyAscii = 0
End If
End Sub
5、只能输入数字:
Private Sub txt?_KeyPress(KeyAscii As Integer) '只能输入数字
If KeyAscii = 8 Then
ElseIf KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0
End If
End Sub
6、限制粘贴:
If KeyCode = vbKeyV And Shift = vbCtrlMask Then
txtPassword.Enabled = False
Clipboard.Clear
txtPassword.Enabled = True
End If
以上也可用键值直接限制,需要什么直接使用对应的键值即可。
Private Sub text1_KeyPress(Index As Integer, KeyAscii As Integer)
Select Case KeyAscii
Case 48 To 57
Case 65 To 90
Case 97 To 122
Case 8
Case Else
KeyAscii = 0
End Select
End Sub
7、文本框弹出提示信息:
比如密码输入次数的提示:
If miCout = 1 Then
MsgBox "您还有两次机会!", 48, "提示"
Exit Sub
End If
又或者能输入什么样的信息、使用什么样的字符、不能如何,都可以适当的给用户做出提示。