Search code examples
excelvalidationvbauserform

VBA Text Box displaying Currency


I have a form with a number of text boxes for user input (this is in a User Form not on the spreadsheet). I have a few boxes that are related to currency and I need them to show the comma and decimal point as the user enters their criteria into the box. So far I have found a bunch of the same formulas online but when I input my number into the box it goes with 4.00 (if i hit 4 first) and all i can change after that is the second 0. Here is something similar I see online:

textbox1 = format(textbox1, "$#,##0.00")

Also seen some with cDbl

No matter what I try it won't let me enter anything more than the first number I enter. I need help. Thanks!


Solution

  • Formatting as the user types in data gets very tricky. May be better to format after the entry is complete.
    Entry can also be validated and old value restored if entry deemed invalid

    Dim TextBox1oldValue As String
    
    Private Sub TextBox1_AfterUpdate()
        If IsNumeric(TextBox1) Then
            TextBox1 = Format(TextBox1, "$#,##0.00")
        Else
            TextBox1 = TextBox1oldValue
        End If
    End Sub
    
    Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
        If IsNumeric(TextBox1) Then
            TextBox1oldValue = Format(TextBox1, "$#,##0.00")
        End If
    End Sub
    
    Private Sub UserForm_Initialize()
        TextBox1oldValue = "$0.00"
        TextBox1 = "$0.00"
    End Sub