2

What is the best way to check if object exists before using set on it ?

I have many workbooks, they contain checkboxes and optionbuttons. I have an array that contain the list of all possible names of checkboxes and optionbuttons that the different workbooks may have

to make my question clear, let us suppose that i have

sArray(i) = "CheckBox15"

when I do

Set s = .OLEObjects(sArray(i))

is giving me an error 1004 when there is no a checkbox called "CheckBox15" in the active sheet.

what I want in my below code, is to add a line that tells :

if "CheckBox15" exists on current sheet (ws) then set .... is there any command that check if an object exists ?

'ws is the worksheet
Dim s As OLEObject
Dim i As Long

with ws
For i = 0 To UBound(sArray)
Set s = .OLEObjects(sArray(i))
If s.Object.Value = True Then
GetOptionCheck = GetOptionCheck & s.Object.Caption
End If
Next i
end with

1 Answer 1

4

You can build a custom boolean function for a quick check:

Public Function objectExists(ByRef ws As Worksheet, ByVal someName As String) As Boolean

    On Error GoTo objectExists_Error

    Dim someOle As OLEObject
    Set someOle = ws.OLEObjects(someName)
    objectExists = True

    On Error GoTo 0
    Exit Function

objectExists_Error:
    objectExists = False

End Function

The call it like this:

Sub TestMe()

    Dim s As OLEObject
    Dim i As Long
    Dim ws As Worksheet: Set ws = Worksheets(1)
    Dim someArray As Variant
    someArray = Array("CheckBox1", "CheckBox2", "CheckBox3", "CheckBox4")

    With ws
        For i = LBound(someArray) To UBound(someArray)
            If objectExists(ws, someArray(i)) Then
                Set s = .OLEObjects(someArray(i))
                Debug.Print s.object.Caption
            End If
        Next i
    End With

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

1 Comment

thanks, your solution works fine, I will choose is as selected solution

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.