Making VBA Form TextBox accept Numbers only (including +, - and .)

后端 未结 7 1218
生来不讨喜
生来不讨喜 2020-12-01 21:46

I have simple textBox and I want to validate its input including \"+\" , \"-\" and \".\" here is what I have tried

Private Sub DisplayValue_TextBox_Change()         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 22:31

    Having relied up till now on string parsing to do this job, I'm glad I decided to check and see how other people do it and found this Q.

    I've refined Ruben Alvarez's excellent answer. The below will allow numerical entries only, and only one decimal point.

    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
    

    This could be further refined to allow only a single "+", "-" etc. as necessary.

提交回复
热议问题