尝试这个:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'Limit the length of the number that can be entered to 12 (This is arbitrary)
If Len(TextBox1.Text) > 12 Then
KeyAscii = 0
Exit Sub
End If
If KeyAscii < 32 Then
Exit Sub ' let it go, it is a control char like backspace
End If
If InStr("0123456789.", Chr$(KeyAscii)) > 0 Then
If InStr(TextBox1.Text, ".") > 0 Then
If Chr$(KeyAscii) = "." Then
KeyAscii = 0 ' do not allow more than one decimal point
Beep
MsgBox "Only 2 decimal places to be allowed", vbCritical
Exit Sub
ElseIf Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 2 Then
KeyAscii = 0 ' do not allow more than 2 digits past decimal point
Beep
MsgBox "Only 2 decimal places to be allowed", vbCritical
Exit Sub
End If
End If
Else
Beep
KeyAscii = 0
End If
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, "$") + 1)) >= 1 Or KeyAscii < 32 Then
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 2 Then
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = Format(TextBox1.Text, "$#,###")
Else
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = TextBox1.Text
End If
ElseIf Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, "$") + 1)) >= 0 Or KeyAscii < 32 Then
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 2 Then
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = Format(TextBox1.Text, "$#,###")
Else
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = ""
TextBox1.Text = "$" & TextBox1.Text
End If
End If
End Sub
Private Sub TextBox1_Change()
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 3 Then
TextBox1.Value = Format(PaidCreditCardForfrm.TextBox1.Value, "$#,###")
End If
End Sub