VBA – TextBox Date Mask (updated)

Máscara de data (e uma pequena homenagem)

A long time ago, I published a hint which coming from the forum that explains how to set a TextBox to have a mask, like date, phone, etc in the link bellow:

https://www.tomasvasquez.com.br/blog/microsoft-office/vba-fomatar-textbox-data-telefone-cpf-nos-eventos-keypress-e-change

The code works well, but it has a bug for date mask. The bug don’t allow ther user to erase all text using the backspace or delete key. Well, after some effort, here is a way to fix it:

Private KeyCodeToAvoid As MSForms.ReturnInteger
 
Private Sub TextBoxData_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Set KeyCodeToAvoid = KeyCode
End Sub
 
Private Sub TextBoxData_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    'Limita a Qde de caracteres
    TextBoxData.MaxLength = 10
 
    'para permitir que apenas números sejam digitados
    If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
        KeyAscii = 0
    End If
 
End Sub
 
Private Sub TextBoxData_Change()
'Formata : dd/mm/aaaa
'não avalia se for backspace ou delete
    If Not (KeyCodeToAvoid = KeyCodeConstants.vbKeyBack Or KeyCodeToAvoid = KeyCodeConstants.vbKeyDelete) Then
        If Len(TextBoxData) = 2 Or Len(TextBoxData) = 5 Then
            TextBoxData.Text = TextBoxData.Text & "/"
            SendKeys "{End}", True
        End If
    End If
    'zera o keycode
    KeyCodeToAvoid = KeyCodeConstants.vbKey0
End Sub

I hope you enjoy it!