我有一个TextBox,我需要让用户只输入-3到3的Single
个数字。
没有字母,没有其他符号。
答案 0 :(得分:2)
首先排除角色。
Private Sub TextBox1_KeyPress(KeyAscii As Integer)
'This will bail out if the backspace key is pressed. That way it will still work to backup in the textbox.
If KeyAscii = 8 Then Exit Sub
'This will allow only numaric values in the text box.
'If (Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9") And KeyAscii <> 45 And KeyAscii <> 46 Then
If (Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9") and Chr(KeyAscii) <> "-" and Chr(KeyAscii) <> "." Then
KeyAscii = 0
End If
End Sub
然后检查输入的内容。
Private Sub TextBox1_Change()
If val(TextBox1.text) < -3 then
TextBox1.text = ""
End If
If val(TextBox1.text) > 3 then
TextBox1.text = ""
End If
End Sub
类似的东西。
答案 1 :(得分:0)
您可以非常简单地使用TextBox_Exit
命令,如下所示:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Select Case Me.TextBox1.Value
Case Is = -3, -2, -1, 1, 2, 3
Case Else:
Me.TextBox1.Value = Null
MsgBox "Only enter single digit numbers from -3 to 3"
End Select
End Sub