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
Image by David Mark from Pixabay