如何限制可以输入的字符

How do I limit what characters can be typed

我想确保在此 TextBox 中只能输入字母。我不想输入 £$ 之类的字符,甚至不想输入数字。我知道如何使用 MaxLength 限制字符的数量,但不知道可以输入哪些字符。

对于VBA你可以分析按键事件中输入的内容。您也可以在 VB.NET 中执行此操作,只是会有所不同。

Private Sub Text4_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    'This will allow only numaric values in the Text4 text box.
    If KeyAscii = 8 Then Exit Sub
    If Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9" Then
        KeyAscii = 0
    End If
End Sub

您还可以查看 KeyDown 事件中的键。如果您得到一个您不想要的密钥,请将 KeyCode 设置为 0Exit Sub 或您想要的。

Private Sub Text4_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
        KeyCode = 0
        DataGrid1.SetFocus
    End If
End Sub

您将查看此处表示的字符的十进制数。 http://www.techonthenet.com/ascii/chart.php

要限制用户可以输入的内容,您可以处理 textboxKeyPress 事件。

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress

    If Not (Asc(e.KeyChar) = 8) Then
        If Not ((Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90)) Then
            e.KeyChar = ChrW(0)
            e.Handled = True
        End If
    End If

End Sub

或者,您可以通过添加一串允许的字符来限制用户输入的内容。如果不允许,则不处理该事件。

If Not (Asc(e.KeyChar) = 8) Then
    Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz"
    If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then
        e.KeyChar = ChrW(0)
        e.Handled = True
    End If
End If