Access VBA:复选框勾选时显示/隐藏按钮(仅用Got/LostFocus事件)
Your current code has a key limitation: it only updates the button's visibility based on the checkbox that currently has focus, not considering the state of all four checkboxes. For example, if you check checkA (hiding the button) then click checkC, the button becomes visible even though checkA is still checked—violating your original requirement.
Here's a fix that adheres to your constraints (only using GotFocus/LostFocus events, avoiding problematic logic that triggers runtime error 2427):
First, create a helper subroutine that evaluates all checkboxes and sets the button's visibility correctly. We use Nz() to handle any null values (which prevents the 2427 error):
Private Sub UpdateJustificationVisibility() ' Hide the button if checkA or checkB is checked (priority rule) Dim hideButton As Boolean hideButton = Nz(Me.checkA.Value, False) Or Nz(Me.checkB.Value, False) If hideButton Then Me.Justification.Visible = False Else ' Show the button only if checkC or checkD is checked Me.Justification.Visible = Nz(Me.checkC.Value, False) Or Nz(Me.checkD.Value, False) End If End Sub
Next, call this helper sub from both the GotFocus and LostFocus events of each checkbox. This ensures the button's visibility updates whenever any checkbox's state might change (either when you click into it or away from it):
' For checkA Private Sub CheckA_GotFocus() UpdateJustificationVisibility End Sub Private Sub CheckA_LostFocus() UpdateJustificationVisibility End Sub ' For checkB Private Sub CheckB_GotFocus() UpdateJustificationVisibility End Sub Private Sub CheckB_LostFocus() UpdateJustificationVisibility End Sub ' For checkC Private Sub CheckC_GotFocus() UpdateJustificationVisibility End Sub Private Sub CheckC_LostFocus() UpdateJustificationVisibility End Sub ' For checkD Private Sub CheckD_GotFocus() UpdateJustificationVisibility End Sub Private Sub CheckD_LostFocus() UpdateJustificationVisibility End Sub
Key Notes:
- Priority Handling: The code prioritizes hiding the button if
checkAorcheckBis checked—even ifcheckCorcheckDare also checked. This aligns with your original requirement. - Error Prevention:
Nz(Me.Control.Value, False)converts any null values (if your checkboxes allow tri-state) toFalse, which avoids runtime error 2427 ("You entered an expression that has no value"). - Comprehensive Updates: Using both
GotFocusandLostFocusensures the button's state is updated in all scenarios (clicking, tabbing, or using keyboard shortcuts to toggle checkboxes).
内容的提问来源于stack exchange,提问作者Imran Khan

