Search code examples
vbaexcelnumbersformat

Format numbers in TextBox as you type


Is there is any way to format numbers in TextBox (on a UserForm) as you type?

This way it makes easy to see what figure is being entered.

My desired format is: #,##0.00


Solution

  • This could be considered a slightly "Above the Average" question in terms of difficulty for a newbie so I am going to answer this :)

    VBA doesn't have what you call a Masked Text Box where you can set formats as #,##0.00. You can only do a masked textbox for accepting passwords but that is altogether a different thing.

    Here is something I quickly came up with. Hope this is what you want?

    Dim CursorPosition As Long
    Dim boolSkip As Boolean
    Dim countCheck As Long
    
    Private Sub TextBox1_Change()
        '~~> This avoids refiring of the event
        If boolSkip = True Then
            boolSkip = False
            Exit Sub
        End If
    
        '~~> Get current cursor postion
        CursorPosition = TextBox1.SelStart
        boolSkip = True
    
        '~~> Format the text
        TextBox1.Text = Format(TextBox1.Text, "#,##0.00")
    
        '~~> Re-position the cursor
        If InStr(1, TextBox1.Text, ".") - 1 > 0 Then _
        TextBox1.SelStart = InStr(1, TextBox1.Text, ".") - 1
    End Sub
    

    You can take it to a slightly higher level by including this code as well. This ensures that the user only types numbers.

    '~~> Numeric Textbox with Decimal Check
    Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
        Select Case KeyAscii
            Case vbKey0 To vbKey9, vbKeyBack, vbKeyClear, vbKeyDelete, _
            vbKeyLeft, vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
                If KeyAscii = 46 Then If InStr(1, TextBox1.Text, ".") Then KeyAscii = 0
            Case Else
                KeyAscii = 0
                Beep
        End Select
    End Sub
    

    In Action

    enter image description here