'**********************************************************************************
' __ _____ ___ . ___ _____ ___ ___
'|__| /\ | | | | | | / | | | | | | | | |\ |
'| /__\ | |--- | | |/\ | | | | | | | | | \ |
'| / \ | | \ | |___ | \ | |___| |___| |__ |___| | \|
'***********************************************************************************
' Fonction de formatage dynamique de textbox avec mask de saisie
'version 3.0
'Date version :17/01/2022
'model : DATEBOX format FR "dd/mm/yyyy"
'
'auteur:patricktoulon
'masque de sasie : "__/__/____" ' il peut etre modifié selon votre souhait
'
'le masque de saisie peut etre visible ou pas
'***********************************************************************************
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
DateBoxMasK TextBox1, KeyCode, False ' le mask de saisie sera invisible
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With TextBox1: Cancel = Not IsDate(.Value) And .Value <> "": End With
End Sub
Private Sub TextBox2_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
DateBoxMasK TextBox2, KeyCode ' le mask de saisie sera visible
End Sub
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With TextBox2: Cancel = Not IsDate(.Value) And .Value <> "": End With
End Sub
Private Sub DateBoxMasK(ByVal TbX As Object, ByVal KeyCode As MSForms.ReturnInteger, Optional MaskVisible As Boolean = True)
Dim V$, K&, Mask$, X&, Pos&
Mask = "__/__/____"
With TbX
V = .Value & Mid(Mask, Len(.Value) + 1) 'on prend la valeur actuelle du textbox
Pos = .SelStart + 1:
Select Case KeyCode
Case 96 To 105, 48 To 57
If Pos = 3 Or Pos = 6 Then Pos = Pos + 1
K = KeyCode:
If K >= 96 Then K = K - 48:
If Pos > 10 Then KeyCode = 0: Exit Sub
Mid(V, Pos, 1) = Chr(K)
If Pos = 2 Or Pos = 5 Then Pos = Pos + 1
'*******Contrôle de la validité de la date*********
If Val(V) > 31 Or Val(Mid(V, 1, 1)) > 3 Then V = Mask: Pos = 0
If Val(Mid(V, 4, 1)) > 1 Or Val(Mid(V, 4, 2)) > 12 Then Mid(V, 4, 2) = Mid(Mask, 4, 2): Pos = 3
If Mid(V, 7, 4) Like "####" Then an = Mid(V, 7, 4) Else an = "2004"
If Mid(V, 1, 5) Like "##/##" Then If Not IsDate(Mid(V, 1, 6) & an) Then Mid(V, 4) = Mid(Mask, 4): Pos = 3
'****fin de Contrôle de la validité de la date*****
KeyCode = 0
Case 8:
If Pos = 7 Or Pos = 4 Then Pos = Pos - 1
If Pos > 1 Then Mid(V, Pos - 1, 1) = Mid(Mask, Pos - 1, 1)
Pos = Application.Max(0, Pos - 2)
KeyCode = 0
Case 13, 9
If .Value <> "" Then If Len(.Value) < 10 Or InStr(1, V, "_") > 0 Then KeyCode = 0
Case 27
V = "": KeyCode = 0
Case Else: KeyCode = 0 'toutes les autres touches sont automatiquement annulées
End Select
If V = Mask Then V = ""
If V <> "" And Not MaskVisible Then V = Split(V, Mid(Mask, 1, 1))(0)
.Value = V
.SelStart = Application.Min(10, Pos)
End With
End Sub