文本框中只允许三个数字值或字符



我想让文本框控件只接受三个数字或字符如何在VB6中做到这一点?

根据您的确切需求,有许多方法可以解决这个问题。如果您只想允许最多3个字符,请这样做:

Option Explicit
Private Sub Form_Load()
Text1.MaxLength = 3
End Sub

如果你只想允许最多3个数字这样做:

Option Explicit
Private Sub Form_Load()
Text1.MaxLength = 3
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
'allow numbers and backspace
If Not (KeyAscii >= 48 And KeyAscii <= 57) And Not KeyAscii = 8 Then KeyAscii = 0
End Sub

如果你只允许3个数字,这样做:

Option Explicit
Private Sub Form_Load()
Text1.MaxLength = 3
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
'allow numbers and backspace
If Not (KeyAscii >= 48 And KeyAscii <= 57) And Not KeyAscii = 8 Then KeyAscii = 0
End Sub
Private Sub Text1_Validate(Cancel As Boolean)
If Len(Text1.Text) <> 3 Then Cancel = True
End Sub

这些例子应该让你开始解决你的问题。

只有三个数字或字符

就是吗?max三个?文本框控件有一个.MaxLength属性,将其设置为"3"。允许三个或更少的字符。但是,可以很容易地在下面的方法中添加固定的精确长度检查。

像这样:

Public Function ValidateTextbox(ByVal txt As TextBox, ByVal allowedChars As String, Optional ByVal caseSensitive As Boolean = True) As Boolean
Dim i As Long, j As Long
Dim sText As String, s As String
Dim bolValidChar As Boolean

sText = txt.Text

For i = 1 To Len(sText)
' Assume False. When the checked character from the textbox
' matches any allowed character, this will be set to True
bolValidChar = False
s = Mid$(sText, i, 1)
For j = 1 To Len(allowedChars)
' Case-sensitive?
If caseSensitive = True Then
If s = Mid$(allowedChars, j, 1) Then
bolValidChar = True
Exit For
End If
Else
If LCase$(s) = LCase$(Mid$(allowedChars, j, 1)) Then
bolValidChar = True
Exit For
End If
End If
Next j

If bolValidChar = False Then
' We've got at least one invalid character -> get outa here!
ValidateTextbox = False
Exit Function
End If
Next i

ValidateTextbox = bolValidChar
End Function

从哪里调用它,例如文本框'ChangeLostFocus事件或代码中的其他地方,取决于您的需求/应用程序设计。

Private Sub txtTest_Change()
Dim sValidChars As String

' sValidChars = "0123456789abcdefghijklmnopqrstuvwxyz"
sValidChars = "0123456789abcdefg"

If ValidateTextbox(txtTest, sValidChars) = False Then
Debug.Print "Invalid character!"
End If
End Sub

相关内容

  • 没有找到相关文章