vb@rchiv
VB Classic
VB.NET
ADO.NET
VBA
C#
SEPA-Dateien erstellen inkl. IBAN-, BLZ-/Kontonummernprüfung  
 vb@rchiv Quick-Search: Suche startenErweiterte Suche starten   Impressum  | Datenschutz  | vb@rchiv CD Vol.6  | Shop Copyright ©2000-2024
 
zurück
Rubrik: Controls · TextBox & RichTextBox   |   VB-Versionen: VB630.03.02
Betragseingaben in der TextBox

Eine universelle Prozedur für Betragseingaben in einer TextBox.

Autor:   Dieter OtterBewertung:     [ Jetzt bewerten ]Views:  21.456 
www.tools4vb.deSystem:  Win9x, WinNT, Win2k, WinXP, Win7, Win8, Win10, Win11 Beispielprojekt auf CD 

Numerische Eingaben oder formatierte Betragseingaben - egal wie - mit unserem heutigen Tipp ist das kein Problem.

Sind z.B. Dezimalstellen erlaubt, so wird bei Eingabe eines Punktes dieser automatisch in ein Komma umgewandelt. Auch wird berücksichtigt, daß ein Komma (oder Punkt) nur einmal eingegeben werden kann.

Fügen Sie zunächst nachfolgenden Code in ein Modul ein:

' Nur Zahlen (optional Komma und Punkt)
Public Sub Check_NumericKey(KeyAscii As Integer, _
  Optional bAllowDecimal As Boolean = True, _
  Optional bAllowNegative As Boolean = True, _
  Optional oText As TextBox = Nothing)
 
  Select Case KeyAscii
    ' Zahlen, Backspace und Return
    Case 48 To 57, 8, 13
 
    ' Minus für Negativ-Zahlen
    Case 45
      KeyAscii = 0
      If bAllowNegative Then
        If Not oText Is Nothing Then
          ' nur zulässig, wenn Cursor an 1. Position
          If (oText.SelStart = 0 Or oText.SelLength = Len(oText.Text)) Then
            KeyAscii = 45
          End If
        End If
      End If
 
    ' Aus Punkt wird autom. Komma
    Case 46, 44
      If bAllowDecimal Then
        If KeyAscii = 46 Then KeyAscii = 44
 
        ' nicht zulässig, falls bereits ein Komma
        ' enthalten
        If Not oText Is Nothing Then
          If InStr(oText.Text, ",") > 0 Then KeyAscii = 0
        End If
      Else
        KeyAscii = 0
      End If
 
    Case Else
      ' alle anderen Zeichen ignorieren
      KeyAscii = 0
  End Select
End Sub
' Betragseingabe formatieren
Public Function Format_Decimal(sValue As String, _
  Optional ByVal nDecimals As Integer = 2) As String
 
  Dim nBetrag As Double
 
  nBetrag = Int(Val(Replace(sValue, ",", ".")) * 10^nDecimals)
  Format_Decimal = Format$(nBetrag / 100, _
    "0." + String$(nDecimals, "0"))
End Function

Anwendungsbeispiel:
In einer TextBox soll ein EUR-Betrag eingegeben werden mit zwei zulässigen Nachkommastellen.

Private Sub txtEuro_KeyPress(KeyAscii As Integer)
  ' Taste prüfen
  Check_NumericKey KeyAscii, , , txtEuro
End Sub
 
Private Sub txtEuro_Validate(Cancel As Boolean)
  ' Eingabe formatieren
 txtEuro.Text = Format_Decimal(txtEuro.Text, 2)
End Sub