问题描述
我有一个问题,是否可以将Telbox中的字段限制为由5位数字组成的数字,例如 11111 22222
我尝试使用宏,但它仅将您限制为数字。
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If Not IsNumeric(Chr(KeyAscii)) Then
MsgBox "Enter a number!"
KeyAscii = 0
End If
End Sub
解决方法
除了KeyPress事件之外,您还可以响应Exit事件来完成此任务:
Option Explicit
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If Not IsNumeric(Chr(KeyAscii)) And Not KeyAscii = 8 Then 'allow for backspace
KeyAscii = 0
End If
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Val(TextBox1.Text) < 10000 Or Val(TextBox1.Text) > 99999 Then
MsgBox "The number must be 5 digits"
Cancel = True
End If
End Sub
,
我尝试了这个,对我有用。 我不是使用.change方法,而是使用了“ beforeupdate”方法
Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If Len(TextBox1.Text) < 5 Then
MsgBox "Please enter Values between 10000 and 99999"
End If
End Sub
Private Sub UserForm_Initialize()
TextBox1.MaxLength = 5
End Sub
也许有帮助