ich benutze folgende Code für die Eingabe von Textfeldern.
Es werden nur Zahlen, zwei Nachkommastellen, ein Komma und ein Minus an erster Stelle erlaubt.
Jedoch kann ich das Komma löschen und an falscher Stelle wieder einsetzten und möchte gerne diesen Bug unterbinden und weiß nicht so recht, wie ich das Abfangen kann?
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'nur Zahlen, ein Komma und nur 2 Stellen nach dem Komma
Select Case KeyAscii
Case Asc("0") To Asc("9")
If InStr(TextBox1, ",") 0 Then
If Len(TextBox1) - InStr(TextBox1, ",") > 1 Then KeyAscii = 0
End If
Case Asc("."), Asc(",")
If InStr(TextBox1, ",") 0 Then
KeyAscii = 0
Else
KeyAscii = Asc(",")
End If
Case Asc(vbBack)
'Eingabe von Minus
Case Asc("-")
Case Else
KeyAscii = 0
End Select
End Sub
Private Sub Textbox1_Change()
'Eingabe von Minus auch nachträglich
Dim BoWert As Boolean
If InStr(TextBox1, "-") >= 1 And Left(TextBox1, 1) "-" Then
TextBox1 = Replace(TextBox1, "-", "")
BoWert = True
ElseIf InStr(TextBox1, "-") = 1 And InStr(2, TextBox1, "-") >= 1 Then
BoWert = True
If Left(TextBox1, 1) = "-" Then
TextBox1 = "-" + Replace(TextBox1, "-", "")
Else
TextBox1 = Replace(TextBox1, "-", "")
End If
End If
'nachträgliche Eingabe von Komma nur an drittletzter Stelle
'bei Eingabe von "," oder "-," wird eine Null vor dem Komma eingesetzt
If Left$(TextBox1.Text, 1) = "," Then
TextBox1.Text = Application.WorksheetFunction.Substitute(TextBox1.Text, ",", "0,")
ElseIf Left$(TextBox1.Text, 2) = "-," Then
TextBox1.Text = Application.WorksheetFunction.Substitute(TextBox1.Text, "-,", "-0,")
End If
End Sub