How to Safely Hide Controls in Microsoft Access

You cannot hide an active control.

If you try to hide the active control, you will get run-time error 2165, "You can't hide a control that has the focus."

To avoid the error, set the focus to a different control first.

For a general solution to this problem, you can use my DefocusIfActive function.

Better yet, let's call a convenience function instead of setting the .Visible property.

Rather than this...

Me.tbMyTextbox.Visible = IsVisible

...use this...

SetCtlVis Me.tbMyTextbox, IsVisible

The Code: SetCtlVis

The SetCtlVis routine wraps the DefocusIfActive procedure so that we avoid run-time error 2165, "You can't hide a control that has the focus."

'----------------------------------------------------------------------------
' Procedure : SetCtlVis
' Author    : Mike Wolfe
' Source    : https://nolongerset.com/setctlvis/
' Purpose   : Sets the visibility of a form control.
' Params    - Ctl: The control whose visibility is being set.
'           - Visibility: A boolean to indicate whether the control 
'                         should be visible or not.
'           - FallbackCtl: The control to receive focus if the original 
'                          Ctl has focus and is being hidden.
' Notes     : If FallbackCtl is not provided, the function will cycle through
'               the form's controls collection looking for a suitable
'               recipient of the focus.
'----------------------------------------------------------------------------
Sub SetCtlVis(Ctl As Control, Visibility As Boolean, _
              Optional FallbackCtl As Control)
    If Visibility Then
        'It's always safe to turn visibility on
        Ctl.Visible = True
    Else
        'https://nolongerset.com/defocusifactive/
        DefocusIfActive Ctl, FallbackCtl
        Ctl.Visible = False
    End If
End Sub

Referenced articles

Fix for the error: “You can’t hide a control that has the focus” in Microsoft Access
The DefocusIfActive() procedure shifts the focus away from a control so that it may be hidden or disabled.
Convenience Functions (My Secret Weapon to Create Self-Commenting Code)
How much can you really gain by replacing one line of code with a different, functionally equivalent line of code? Quite a bit, as it turns out.

Image by David Mark from Pixabay