Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error on textbox text change event VBA form

I have a textbox named "txtEndBalance" in a form I want only numbers to be inserted as a part of data validation. Therefore I have On Error event.

Now when I fire up the form via a button. It directly goes to the error and I have a message box pop up "Invalid currency amount". This wasn't supposed to be like this.

And then when I get rid of the pop up trying to enter a number. And right when I enter a single digit number it throws that error again.

I have no idea where I am wrong in the code below because I think I did everything right.

Have look at the file here if you need.

Private Sub txtEndBalance_Change()

    On Error GoTo Error:

    Dim amt As Currency
    amt = txtEndBalance
    txtEndBalance = Format(amt, "$##,###,##0")
    Exit Sub

Error:
        If txtEndBalance <> "$" And txtEndBalance <> "" Then
        MsgBox "Invalid currency amount", , "Error"
        txtEndBalance = Format(0, "$##,###,##0")
        End If

End Sub
like image 857
Stupid_Intern Avatar asked Jan 24 '26 13:01

Stupid_Intern


1 Answers

This will make it so only numbers can be entered. Put in this KeyPress event.

Private Sub txtEndBalance_KeyPress(KeyAscii As Integer)

    'This is a check for backspace keypress.
    If KeyAscii = 8 Then Exit Sub

    'This will allow only numeric values in the text box.
    If Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9" Then
        KeyAscii = 0
    End If
End Sub

Then you can do your formatting in the change event.

like image 84
MatthewD Avatar answered Jan 27 '26 05:01

MatthewD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!