Using KeyPress Event to Format Numbers

business_analyst

Board Regular
Joined
Jun 5, 2009
Messages
99
Hello All,

I have textbox on a Userform that allows the user to enter a dollar amount from 1 to 99,999,999. I was trying to input code into the KeyPress event of the textbox to that while the user is entering an amount, the number is automatically split with commas. This is the code I have:

Code:
Private Sub txt_spend_Keypress(ByVal KeyAscii As MSForms.ReturnInteger)
    Dim num As String

    If KeyAscii < 47 Or KeyAscii > 57 Then
        KeyAscii = 0
    End If
    
    If txt_spend.Value <> "" Or txt_spend.Value <> 0 Then
        txt_spend = Format(txt_spend, "#,###")
    End If
End Sub

However, this code does not seem to be working properly. It actually inputs the comma after the fourth digit, for example: 12345 becomes 1,2345.

I am not sure why it is doing this, I have even tried changed around the format from: "#,###" to "##,###" to "###,###". All giving the same issue. Any help would be greatly appreciated.
 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Try this:
Code:
Private Sub txt_spend_Keypress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then KeyAscii = 0
End Sub

Private Sub txt_spend_Change()
    txt_spend.Text = Format(txt_spend.Value, "#,##0")
End Sub
 
Upvote 0
Try this:
Code:
Private Sub txt_spend_Keypress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then KeyAscii = 0
End Sub

Private Sub txt_spend_Change()
    txt_spend.Text = Format(txt_spend.Value, "#,##0")
End Sub

Thank you SO MUCH for this!!
 
Upvote 0

Forum statistics

Threads
1,215,061
Messages
6,122,922
Members
449,094
Latest member
teemeren

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top