键入时格式化 TextBox 中的数字

Format numbers in TextBox as you type

有什么方法可以在您键入时格式化文本框中的数字(在用户窗体上)

这样可以很容易地看到正在输入的数字。

我想要的格式是:#,##0.00

就新手的难度而言,这可能被认为是一个稍微“高于平均水平”的问题,所以我要回答这个问题:)

VBA 没有所谓的屏蔽文本框,您可以在其中将格式设置为 #,##0.00。您只能做一个用于接受密码的屏蔽文本框,但这完全是另一回事。

这是我很快想到的。希望这就是你想要的?

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

您也可以通过包含此代码将其提升到更高的层次。这可确保用户仅键入数字。

'~~> 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

在行动

试试看:

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