Format numbers in TextBox as you type

浪子不回头ぞ 提交于 2021-01-29 01:33:34

问题


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


回答1:


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




回答2:


Try that:

Private Sub Text1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode > 47 And KeyCode < 58 Then
        Text1.Tag = Text1.Tag & Chr$(KeyCode)
    ElseIf KeyCode = vbKeyBack And Len(Text1.Tag) > 0 Then
        Text1.Tag = Left$(Text1.Tag, Len(Text1.Tag) - 1)
    End If

    Text1 = FormatCurrency$(Val(Text1.Tag) / 100, 2, vbTrue, vbFalse, vbTrue)
    Text1.SelStart = 65535
    KeyCode = 0

End Sub


来源:https://stackoverflow.com/questions/32421055/format-numbers-in-textbox-as-you-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!