Search code examples
ms-accesscheckboxvbavisible

Setting a checkbox to Visible = False


I'm trying to make a checkbox disappear if a field is empty using the following code:

If rstPIANO.RecordCount <= 0 Then
    MsgBox "No PIANO Data exists for this date"
    chkPIANO.Enabled = Not (chkPIANO.Enabled)
    chkPIANO.Visible = False
    Else
        chkPIANO.Visible = True
    End If

When I try this the msgbox works, then I get run-time error '91': Object variable or With block variable not set? I do initialize the checkbox earlier in the code with

Dim chkPIANO As Checkbox

Any thoughts on fixing this issue?


Solution

  • After ...

    Dim chkPIANO As Checkbox
    

    You must Set it to something. If the code is running on the form which contains the check box ...

    Set chkPIANO = Me.CheckBoxName
    

    But if the name of the check box control is chkPIANO, you don't need to declare a variable with the same name. You should be able to refer to it as ...

    Me.chkPIANO
    

    If your code is in a standard module instead of the form's module ...

    Set chkPIANO = Forms!YourFormName!CheckBoxName
    

    As basic practice, add Option Explicit to the Declarations section of your module and then run Debug->Compile from the VB Editor's main menu. Fix anything the compiler complains about. Use Option Explicit in all your code modules.