Search code examples
excelvbatextbox

Limit number of digits after comma in textbox


I have a textbox in userform which will be filled only with digits, commas, or dots. I know how to restrict use of only those characters. My question is it possible to limit filling value to 2 digits after coma/dot?

So when I enter value like: 1023,456 it would not let me type 6 without any action.

Editted:
I can't get this... I tried testing codes given here: Regex to match 2 digits, optional decimal, two digits However it matches too many things. When I type more then 2 digits after comma it still matches as good string. I used for example:

\d{0,2}(\,\d{1,2})?
[0-9]?[0-9]?(\,[0-9][0-9]?)?

What I am doing wrong?

Private Sub netto_Change()

Dim regEx As New VBScript_RegExp_55.RegExp

regEx.Pattern = "\d{0,2}(\,\d{1,2})?"

If regEx.Test(netto.Value) = True Then MsgBox ("It works!")

End Sub

Edit 2:
Okay, I am really close I got this code: ^[0-9]+[\,\.]?[0-9]?[0-9]$ but one thing is missing. This pattern should also apply to string like: 321, with comma\dot at the end but without anything after that.

What to do?


Solution

  • I found some time to think and I came up with a different idea on how to cope with that.

    First of all I used KeyPress event to prevent input of any characters different then 0-9, comma and dot. To make my code work as I wanted I added code to Change event. If sentence checks whether there is comma or dot in my texbox input. If it is, limits maxlength.

    Private Sub netto_Change()
    
    Dim znaki As Byte
    
    znaki = Len(netto.Value)
    
    
    If InStr(1, netto.Value, ".", vbTextCompare) > 0 Or InStr(1, netto.Value, ",", vbTextCompare) > 0 Then
    
        If netto.MaxLength = znaki + 1 Or netto.MaxLength = znaki Then
    
        Else
        netto.MaxLength = znaki + 2
    
        End If
    
    Else
    netto.MaxLength = 0
    
    End If
    
    End Sub
    
    Private Sub netto_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    
    Select Case KeyAscii
    
        Case Asc("0") To Asc("9")
        Case Asc(",")
        Case Asc(".")
        Case Else
        KeyAscii = 0
    
    End Select
    
    End Sub