我在MS Access中的表单中有一个文本框。我只想让用户输入字母和空格。没有特殊字符。
我已在KeyPress
事件中实施了以下内容。我想知道有没有更好的方法来实现相同的。
Private Sub txtName_KeyPress(KeyAscii As Integer)
If KeyAscii <> 8 And KeyAscii <> 32 Then 'Not Backspace (important for error correction) and not a Space
If (KeyAscii < 65 Or KeyAscii > 90) And (KeyAscii < 97 Or KeyAscii > 122) Then 'Allowing lower and upper case
Beep 'Let the user know they hit an illegal key
KeyAscii = 0 'Don't let the keystroke through
End If
End If
End Sub
答案 0 :(得分:4)
考虑使用文本框的BeforeUpdate事件,这是通常用于验证条目的触发器,因为您可以取消更新:
Private Sub txtWordsOnly_BeforeUpdate(Cancel As Integer)
If Me.txtWordsOnly Like "*[0-9]*" Or Me.txtWordsOnly Like "*[@#$%*^&?()<>/\'""!]*" Then
MsgBox "Invalid entry. Please select only words," _
& " NOT numbers or special characters.", vbInformation
Cancel = -1 ' OR Cancel = True
Me.txtWordsOnly.Undo
End If
End Sub
答案 1 :(得分:3)
使用验证规则。
Allen Browne在此处有一个非常有用的验证规则列表:
http://allenbrowne.com/ValidationRule.html
Is Null Or Not Like "*[!a-z OR "" ""]*"
标点符号和数字被拒绝。