一、文本框限定
1、限定输入的字符长度
文本框中有个MaxLength属性,输入自己要限定的数字即可;也可以利用代码来限定,当超过限定长度时,弹出警告对话窗
1. Private sub txtUserName_change() 2. If Len(Trim(txtUserName)) > 4 then 3. MsgBox "姓名不能超过4个字符,请重新输入!", 0 + 48 4. txtUserName = "" 5. End if 6. End iSub
Trim函数是消除字符串的空格,Len函数是计算字符串的长度
2、限定特殊字符
1. Private Sub txtUserName_Change() 2. If Len(Trim(txtUserName)) > 4 then 3. MsgBox "姓名不能超过4个字符,请重新输入!", 0 + 48 4. txtUserName = "" 5. End if 6. End sub
3、限定输入的字符类型
1. Private Sub txtSID_KeyPress(KeyAscii As Integer) 2. Const xStr As String = "123456" '只能输入数字 3. KeyAscii = IIf(Instr(xStr & Chr(8), Chr(KeyAscii)), KeyAscii, 0) 4. End Sub
4、限定特殊字符
1. Private Sub txtDirector_KeyPress(KeyAscii As Integer) 2. Select Case KeyAscii 3. Case 8 '限制退格键 4. Case Asc("A") To ("Z") 5. Case Asc("a") To ("z") 6. Case Is < 0 7. Case Else 8. KeyAscii = 0 9. MsgBox "格式错误,请输入汉字或英文!", 0 + 48 10. txtDirector.Text = "" 11. End Select 12. End Sub
5、只能输入数字
1. If keyAscii = 8 Then Exit Sub 2. If keyAscii < 48 Or keyAscii > 57 Then keyAscii = 0
6、限制数字大小,这个适合成绩对话框
1. Private Sub txtResult_change() 2. On Error Resume Next 3. If Val(Trim(txtResult.Text)) > 100 Then 4. MsgBox "输入数字过大,请重新输入" 5. txtResult.Text = "" 6. End If 7. End Sub
7、不能输入特殊字符(和第二、四个一样的性质)
1. Select Case keyAscii 2. Case -20319 To -3652 3. Case 48 To 57 4. Case 65 To 98 5. Case 97 To 122 6. Case 8 7. Case Else 8. keyAscii = 0 9. End Select
8、限定特殊字符、数字、空格,只能输入汉字和字母
1. Private Sub txtCourseName_KeyPress(KeyAscii As Integer) 2. If KeyAscii < 0 or KeyAscii = 8 or KeyAscii = 13 Then 3. Else If 4. Not chr(KeyAscii) Like "[a-ZA-Z]" Then 5. keyAscii = 0 6. End if 7. End sub
二、下拉框限定
Combox限定不能键盘输入,只能选择下拉框里面的内容
1. Private Sub comboGrade_KeyPress(KeyAscii As Integer) 2. KeyAscii = 0 '限制键盘不能输入内容 3. End Sub
三、限定成绩
1. Private Sub txtResult_Change() 2. If Val(txtResult.Text) > 120 Or Val(txtResult.Text) < 0 Then 3. MsgBox "请输入成绩在0~120范围内!", 0 + 48 4. txtResult.Text = "" 5. End If 6. End Sub
四、限定不能复制粘贴
在第二次输入密码时,不能复制粘贴
1. Private Sub txtPassword1_KeyDown(KeyCide As Integer, Shift As Integer) 2. If (KeyCode = 86 Or KeyCode = 67 Or KeyCode = 88) And Shift = 2 Then 3. MsgBox "不能复制粘贴", 0 + 48 4. txtPassword1.Text = "" 5. End If 6. End Sub
提示密码剩余次数
1. If miCout = 1 Then 2. MsgBox "您还有两次机会", 0 + 48,"提示" 3. Exit sub 4. End If 5. 6. If miCout = 2 Then 7. MsgBox "您还有一次机会", 0 + 48,"提示" 8. Exit sub 9. End If 10. 11. If miCout = 3 Then 12. MsgBox "即将关闭程序", 0 + 48,"提示" 13. Me.Hide 14. Exit sub 15. End If