VBA在设置之前检查对象是否存在

时间:2019-03-01 14:01:22

标签: excel vba

在使用set之前检查对象是否存在的最佳方法是什么?

我有很多工作簿,其中包含复选框和选项按钮。 我有一个数组,其中包含不同工作簿可能具有的复选框和选项按钮的所有可能名称的列表

为了明确我的问题,让我们假设我有

sArray(i) = "CheckBox15"

当我这样做

Set s = .OLEObjects(sArray(i))

当活动工作表中没有名为“ CheckBox15”的复选框时,

给我一​​个错误1004

我想在下面的代码中添加一行内容:

如果当前工作表(ws)上存在“ CheckBox15”,则设置....是否有任何命令检查对象是否存在?

'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 个答案:

答案 0 :(得分:3)

您可以构建自定义布尔函数以进行快速检查:

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

像这样打电话:

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
相关问题