2014-10-01 113 views
1

我有简单的文本框,我想验证其输入包括“+”,“ - ”和“。”。这里是我试图使VBA表单文本框只接受数字(包括+, - 和)

Private Sub DisplayValue_TextBox_Change() 
If Not IsNumeric(DisplayValue_TextBox.Value) Then 
       MsgBox "Only numbers allowed" 

     End If 
End Sub 

但这只接受数字0-9无负,正值或浮点数值..

+0

因为'Textbox_Change()'火灾每次出现在文本框中输入一个新的角色。您应该考虑使用不同的事件,例如'_Exit()'或'_AfterUpdate()'来验证失去焦点的值,例如 – 2014-10-01 10:17:14

回答

5

而且我的评论:

考虑一个样品Userform1用Textbox1的和CommandButton1的

enter image description here

当你进入在 TextBox1任何

变化事件触发 - 即。输入一个字符触发Change()事件并传递当前值,所以即使当您输入负号时,当前的逻辑失败。

你需要的是对第二个使用像_AfterUpdate()_Exit()另一个事件与amphasis,因为你可以取消事件:)

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 

你可以在这里找到事件:

enter image description here

3

使用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 
0

已经依赖到现在的字符串解析做这个工作,我很高兴我决定去检查,看看别人怎么做的,发现了这个问题:

我精鲁本·阿尔瓦雷斯的出色答卷。下面将只允许数字输入,并且只有一个小数点。

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 

根据需要,可以进一步细化为只允许一个“+”,“ - ”等。

0

即时通讯使用:

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