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.
 

John_w

MrExcel MVP
Joined
Oct 15, 2007
Messages
5,996
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
 

neothingol

New Member
Joined
Jul 23, 2015
Messages
1
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!!
 

Forum statistics

Threads
1,081,730
Messages
5,360,937
Members
400,602
Latest member
newaqua

Some videos you may like

This Week's Hot Topics

  • populate from drop list with multiple tables
    Hi All, i have a drop list that displays data, what i want is when i select one of those from the list to populate text from different tables on...
  • Find list of words from sheet2 in sheet1 before a comma and extract text vba
    Hi Friends, Trying to find the solution on my task. But did not find suitable one to the need. Here is my query and sample file with details...
  • Dynamic Formula entry - VBA code sought
    Hello, really hope one of you experts can help with this - i've spent hours on this and getting no-where. .I have a set of data (more rows than...
  • Listbox Header
    Have a named range called "AccidentsHeader" Within my code I have: [CODE]Private Sub CommandButton1_Click() ListBox1.RowSource =...
  • Complex Heat Map using conditional formatting
    Good day excel world. I have a concern. Below link have a list of countries that carries each country unique data. [URL...
  • Conditional formatting
    Hi good morning, hope you can help me please, I have cells P4:P54 and if this cell is equal to 1 then i want row O to say "Fully Utilised" and to...
Top