如何检查是否存在任何形状?

时间:2016-05-12 07:21:18

标签: excel vba

如何检查工作表中是否存在任何形状?

我使用了以下代码:

Sub my()
    Dim shp As Shape
    If Not shp Is Nothing Then
        For Each shp In Sheet1.Shapes
            mesage = shp.TopLeftCell.Address(0, 0)
        Next shp
    Else
        mesage = Sheet1.Cells(1, 12).Address
    End If

End Sub

由于我没有给出形状名称,它正在执行'if-else'循环的'else'部分。

我不能在这里给出形状名称,因为每次形状名称都不同。

1 个答案:

答案 0 :(得分:2)

检查是否存在任何个形状

如果要检查活动工作表上是否有任何 VBA Shapes,则只需检查.Count propertyShapes object的值即可:

ActiveSheet.Shapes.Count

...,它将返回形状的数量,如果没有形状,则返回

用法示例:

If ActiveSheet.Shapes.Count = 0 Then MsgBox "No shapes found!"

检查是否存在特定形状

如果需要检查是否存在 特定 形状,请使用以下功能:

Function shapeExists(shapeName As String) As Boolean
'returns TRUE if a shape named [ShapeName] exists on the active worksheet
    Dim sh As Shape
    For Each sh In ActiveSheet.Shapes
         If sh.Name = shapeName Then shapeExists = True
    Next sh
End Function

用法示例:

If Not shapeExists("My Shape Name") Then MsgBox "Shape not found!"

列出所有形状

在立即窗口中列出活动工作表上的所有形状。 (按 Ctrl + G 将其打开。)

Sub ListAllShapes()
'list all shapes on the active worksheet
    Dim sh As Shape
    For Each sh In ActiveSheet.Shapes
        Debug.Print "id=" & sh.ID, "name=" & sh.Name
    Next sh
End Sub

删除所有形状

从活动工作表中删除所有形状。

Sub DeleteAllShapes()
'delete all shapes on the active worksheet (Including CONTROLS, so use with caution!)
    Dim sh As Shape
    For Each sh In ActiveSheet.Shapes
        sh.Delete
    Next sh
End Sub

更多信息:

有关使用VBA Shapes的更多详细信息和示例,请参阅我对与其他 Shape相关问题(包括 control 只是Shape的另一种形式)的回答: