我有简单的textBox,我想验证它的输入,包括“+”,“ - ”和“。”。这是我尝试过的
Private Sub DisplayValue_TextBox_Change()
If Not IsNumeric(DisplayValue_TextBox.Value) Then
MsgBox "Only numbers allowed"
End If
End Sub
但是这只接受数字0-9没有负数,正值或浮点值。
继我的评论:
考虑一个带有Textbox1和CommandButton1的示例Userform1
当您在TextBox1
中输入任何内容时,更改事件将触发 - 即。键入一个字符会触发Change()
事件并传递当前值,因此即使您键入负号,您当前的逻辑也会失败。
你需要的是使用另一个事件,如_AfterUpdate()
或_Exit()
,重点是第二个,因为你可以取消事件:)
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Not IsNumeric(TextBox1.Value) Then
MsgBox "only numbers allowed"
Cancel = True
End If
End Sub
你可以在这里找到活动:
使用KeyPress事件,并丢弃任何非数字条目:
Private Sub txtShift1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Debug.Print KeyAscii
If KeyAscii >= 48 And KeyAscii <= 57 Then
Debug.Print "number"
Else
Debug.Print "other"
KeyAscii = 0
End If
End Sub
到目前为止依靠字符串解析来完成这项工作,我很高兴我决定检查并查看其他人是如何做到的并找到了这个Q.
我已经完善了Ruben Alvarez的优秀答案。下面只允许数字输入,只允许一个小数点。
Private Sub txtShift1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case 46
If InStr(1, txtShift1, ".") > 0 Then KeyAscii = 0
Case 48 To 57
Case Else
KeyAscii = 0
End Select
End Sub
这可以进一步细化,以便在必要时仅允许单个“+”,“ - ”等。
我用它:
Private Sub txtGiaNet_Change()
If IsNumeric(txtGiaNet.Value) Then
//if number do sth
Else
//if not, delete this character
txtGiaNet.Value = Left(txtGiaNet.Value, Len(txtGiaNet.Value) - 1)
End If
End Sub