30 December 2022

MS Access - Specify Max Length for TextBox or ComboBox on a Form

You should limit both events:
  • KeyPress() for user typing
  • Change() for copy/paste
Public Sub LimitKeyPress(ByRef pControl As Control, pMaxLen As Long, ByRef KeyAscii As Integer)

    On Error GoTo GesErr

'   -------------------------------------------------------------------------
'   -- GESTIONE MAX LENGTH IN UNA TEXTBOX/COMBO UNBOUND 1/2: KeyPress
'   -------------------------------------------------------------------------
'   Via:          http://allenbrowne.com/ser-34.html
'
'   Utilizzo:     Nella KeyPress():
'                   Private Sub Testo0_KeyPress(KeyAscii As Integer)
'                       LimitKeyPress Me.ActiveControl, cMaxLen, KeyAscii
'                   End Sub
'
'   NB:           Ricordarsi di lanciare anche la LimitChange()
'   -------------------------------------------------------------------------
    
    With pControl
        If Len(pControl.Text) - .SelLength >= pMaxLen Then
            If KeyAscii <> vbKeyBack Then
                KeyAscii = 0
            End If
        End If
    End With
    
    Exit Sub
    
GesErr:
    SysGesErr , StringFormat("LimitKeyPress({0}, {1}, {2})", pControl.name, pMaxLen, KeyAscii)
    
End Sub

Public Sub LimitChange(ByRef pControl As Control, pMaxLen As Long)

    On Error GoTo GesErr

'   -------------------------------------------------------------------------
'   -- GESTIONE MAX LENGTH IN UNA TEXTBOX/COMBO UNBOUND 2/2: Copy/Paste
'   -------------------------------------------------------------------------
'   Via:          http://allenbrowne.com/ser-34.html
'
'   Utilizzo:     Nella Change():
'                   Private Sub Testo0_Change()
'                       LimitChange Me.ActiveControl, cMaxLen
'                   End Sub
'
'   NB:           Ricordarsi di lanciare anche la LimitKeyPress()
'   -------------------------------------------------------------------------

    With pControl
        If Len(.Text) > pMaxLen Then
            .Text = Left(.Text, pMaxLen)
            .SelStart = pMaxLen
        End If
    End With
    
    Exit Sub

GesErr:
    SysGesErr , StringFormat("LimitChange({0}, {1})", pControl.name, pMaxLen)
    
End Sub


Using in the Form:
Private Sub Testo0_KeyPress(KeyAscii As Integer)
    LimitKeyPress Me.ActiveControl, cMaxLen, KeyAscii
End Sub

Private Sub Testo0_Change()
    LimitChange Me.ActiveControl, cMaxLen
End Sub
Via: http://allenbrowne.com/ser-34.html