應用程式/阻止非法字元的 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