2014-10-01 56 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 
相關問題