1

hi i have a checkbox and code if i run it shows error. please rectify this error.

Private Sub CheckBox1_Click()
    With Sheets("bom")
        If .CheckBox1.Value = True Then
            .Range("show_all_level") = "Yes"
        Else
            .Range("show_all_level") = "No"
        End If
    End With
End Sub

type of error:

enter image description here

9
  • 1
    You probably don't have a defined range called "show_all_level" . Check in your Formula tab>Name Manager and see if you have a defined range called "show_all_level" ? Commented Apr 11, 2017 at 19:03
  • 1
    Is the defined named range show_all_level on the same worksheet as the checkbox? i.e. Worksheets("bom") Commented Apr 11, 2017 at 19:21
  • More importantly, is the CheckBox1 on Sheet bom? Commented Apr 11, 2017 at 19:47
  • Yes, it is in Sheet("bom") Commented Apr 11, 2017 at 20:00
  • Which line is highlighted when the error occurs? Commented Apr 11, 2017 at 21:32

1 Answer 1

1

Try the code below, it should handle different scenarios you might have with your "show_all_level" Name Range.

Option Explicit

Private Sub CheckBox1_Click()

Dim Nm          As Name
Dim NmExist     As Boolean
Dim NameRng     As Range

' loop through all Name Ranges in ThisWorkbook
For Each Nm In ThisWorkbook.Names
    If Nm.Parent.Name Like "bom" Then '<-- check if name range parent (Sheet.Name) is "bom"
        MsgBox Nm.Name & " Name Range exists is sheet " & Chr(34) & Nm.Parent.Name & Chr(34)
        NmExist = True ' raise the flag >> Name exist in "bom" sheet
        Set NameRng = Nm.RefersToRange ' set the Range to the Name Range
        Exit For
    ElseIf Nm.Parent.CodeName Like "ThisWorkbook" Then '<-- check if name scope is "ThisWorkbook"
        MsgBox Nm.Name & " Name Range exists as WorkBook scope"
        NmExist = True ' raise the flag >> Name exist in Workbook scope
        Set NameRng = Nm.RefersToRange ' set the Range to the Name Range
        Exit For
    End If
Next Nm

' verify that "show_all_level" name exist in "bom" sheet (or Workbook scope)
If Not NmExist Then
    MsgBox Chr(34) & "show_all_level" & Chr(34) & "Name Range, doesn't exist in the desired sheet", vbCritical
    Exit Sub
End If

With Sheets("bom")
    If .CheckBox1.Value = True Then
        NameRng.Value = "Yes"
    Else
        NameRng.Value = "No"
    End If
End With

End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

@DINESHKUMARPALANISAMY see meta.stackexchange.com/a/5235/289619
@0m3r thanks for this link ;) I have needed it in the past so many times ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.