vb 的 我想规定text文本框中只允许输入4个数字

来源:百度知道 编辑:UC知道 时间:2024/05/28 11:40:14
多一个少一个都不行怎么办呢?
如果我输入了3个数字,也不行,必须输4个,同志们的回答是大于4个时的情况吧

'设置Text1文本最大长度为4
Private Sub Form_Load()
Text1.MaxLength = 4
Text1 = ""
End Sub

'屏蔽掉除数字键,Backspace和Delete之外的按键,同时屏蔽Ctrl + V粘贴
Private Sub Text1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 8, 46, 48 To 57

Case Else
KeyAscii = 0

End Select
End Sub

'在失去焦点时用0补足4位
Private Sub Text1_LostFocus()
Text1.Text = Format(Text1, "0000")
End Sub

另外需要注意用api屏蔽掉文本框默认的右键菜单,代码太长而且网上很多,楼主自己找来用吧

Private Sub Text1_Change()
If Len(Text1.Text) > 4 Then Text1.Text = Left(Text1.Text, 4)
End Sub
Private Sub Text1_LostFocus()
If Len(Text1) < 4 Then
MsgBox "长度不够!"
Text1.SetFocus
End If
End Sub

有个这样的属性吧,好像叫Maxlength
写4就行
没有的话就用楼上的