应用程序/阻止非法字符的 Visual Basic
外观
此 VBA 示例可以在任何常用的 Microsoft Office 应用程序中运行。这些示例展示了如何在按键时从文本框中排除非法字符。在这两个示例中,当输入非法字符时,插入点只是停留在它所在的位置;接受的字符将以通常的方式显示。这两个示例都使用了TextBox_KeyPress 事件;第一个示例只接受整数和其他几个字符,第二个示例只接受字母和一些支持字符。
'...............................................
' Notes: Code needs a user form named UserForm1,
' with two text boxes, TextBox1 and Textbox2,
' and a command button with name CommandButton1.
' Set UserForm1 property ShowModal to False
'...............................................
Private Sub Workbook_Open()
'Runs on opening the workbook
Load UserForm1
UserForm1.Show
End Sub
- 确保用户窗体的ShowModal 属性设置为False,以允许正常代码工作并与打开的窗体一起学习。
- 将以下代码复制到 UserForm1 模块中,然后在框中输入文本以查看结果。
- 在代码中将参数KeyAscii 设置为非打印字符的 ASCI 值(例如:零),可以防止显示导致事件的字符。否则,KeyAscii 将包含所按键的 ASCI 值,并将显示该值。
- KeyAscii 值可以更改为任何 ASCII 值,并且只要它是一个可打印字符,它就会被显示。
- 在每种情况下,都会添加代码来限制文本中允许的位置。例如,减号仅在数字开头有效,连字符在单词开头永远不会出现。
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'Block character input other than integers, minus signs, and periods
'For example, to enter a number and decimal, eg; -4756.09
Select Case KeyAscii
'accept integers
Case Asc("0") To Asc("9")
Case Asc("-") ' unless one already exists or cursor not at start
If InStr(1, Me.TextBox1.Text, "-") > 0 Or Me.TextBox1.SelStart > 0 Then
KeyAscii = 0 'return a non-printing character
End If
Case Asc(".") 'unless one exists already
If InStr(1, Me.TextBox1.Text, ".") > 0 Then
KeyAscii = 0 'return a non-printing character
End If
Case Else
KeyAscii = 0 'return a non-printing character
End Select
End Sub
Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'Block character input other than letters, hyphens, periods, and space
' For example, for title, forename and surname, eg; Mr. John Doe.
Select Case KeyAscii
'accept upper and lower case letters
Case Asc("a") To Asc("z"), Asc("A") To Asc("Z")
Case Asc("-"), Asc("."), Asc(" ")
'ok provided on at least the third character
If Me.TextBox2.SelStart < 2 Then 'zero is first
KeyAscii = 0 'return a non-printing character
End If
Case Else
KeyAscii = 0 'return a non-printing character
End Select
End Sub