键入时格式化 EXCEL/VBA

Format while typing EXCEL/VBA

经过一些搜索,我找到了 Siddharth Rout 代码,用于在键入时格式化文本框,但没有明显的原因,它给了我一个错误的格式或无限格式。

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, "###-###.###-###")

'~~> Re-position the cursor
If InStr(1, TextBox1.Text, ".") - 1 > 0 Then _
TextBox1.SelStart = InStr(1, TextBox1.Text, ".") - 1
End Sub

想法是用户键入类似“123456789852”的 12 位数字,并在键入时格式化为“123-456.789-852”,因为这样更容易发现任何输入错误。

亲切的问候

如果任何其他答案都失败了,您可以尝试这个非常丑陋的解决方案:

Private Sub TextBox1_Change()

If Len(TextBox1.Text) = 3 And TextBox1.Text Like "###" = True Then TextBox1.Text = TextBox1.Text & "-"
If Len(TextBox1.Text) = 7 And TextBox1.Text Like "###-###" = True Then TextBox1.Text = TextBox1.Text & "."
If Len(TextBox1.Text) = 11 And TextBox1.Text Like "###-###.###" = True Then TextBox1.Text = TextBox1.Text & "-"
If Len(TextBox1.Text) > 15 Then TextBox1.Text = Left(TextBox1.Text, 15)

End Sub