将用户输入限制为用户窗体文本框上的整数
我在一个用户窗体上有一个文本框,试图将用户输入限制为仅允许整数值.我能够做到这一点,但是这种行为有点怪异.首先,这是我的代码:
I have a textbox on a userform that I am trying to restrict user input to only allow integer values. I am able to do this, but the behavior is a little weird. First, here is my code:
Private Sub txtAnswer_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If (KeyAscii >= 48) And (KeyAscii <= 57) Then
Me.txtAnswer.SetFocus
Else
KeyAscii = 0
Me.txtAnswer.SetFocus
End If
End Sub
问题在于,用户输入值后,焦点似乎离开了文本框.此外,如果用户确实输入了整数值,那么将从文本框中删除该值(即输入被吃掉").SetFocus行是我试图使控件正确运行的尝试,但它们似乎没有任何作用.
The problem is that after the user has entered a value, the focus seems to go away from the textbox. Further, if the user does enter an integer value, this value is deleted from the textbox (i.e. the input gets "eaten"). The SetFocus lines are my attempt to make the control behave correctly, but they seem to have no effect.
我要做的就是确保用户未在文本框中输入"r"(或任何其他非整数值)之类的内容.任何大于等于0的整数值都是完全可以接受的(包括10或1000000等多个数字值).
All I want to do is make sure that the user doesn't enter something like "r" (or any other non-integer value) in the textbox. Any integer value >= 0 is perfectly acceptable (including multiple digit values like 10 or 1000000).
有人可以看到为什么我的方法行不通吗?我尝试了几种不同的方法,并进行了很多搜索,但找不到有效的方法.
Can anybody see why my approach isn't working? I've tried a few different approaches and have searched around quite a bit, but I can't find something that works.
谢谢
提前一步!
'~~> Disable Pasting CTRL V , SHIFT + INSERT
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If (Shift = 2 And KeyCode = vbKeyV) Or (Shift = 1 And KeyCode = vbKeyInsert) Then
KeyCode = 0
End If
End Sub
'~~> Preventing input of non numerics
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case vbKey0 To vbKey9, vbKeyBack, vbKeyClear, vbKeyLeft, _
vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
Case Else
KeyAscii = 0
Beep
End Select
End Sub