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

Abh*_*eet 6 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
Run Code Online (Sandbox Code Playgroud)

由于我没有给出形状名称,因此它正在执行“ If-else”循环的“ else”部分。

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

ash*_*awg 11

检查是否存在任何形状

如果要检查是否有任何 VBA形状活动工作表上,那么你可以简单地检查的价值.Count属性的的Shapes对象

ActiveSheet.Shapes.Count
Run Code Online (Sandbox Code Playgroud)

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

示例用法:

If ActiveSheet.Shapes.Count = 0 Then MsgBox "No shapes found!"
Run Code Online (Sandbox Code Playgroud)

检查特定形状是否存在

如果您需要检查特定形状是否存在,请使用此函数:

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
Run Code Online (Sandbox Code Playgroud)

用法示例:

If Not shapeExists("My Shape Name") Then MsgBox "Shape not found!"
Run Code Online (Sandbox Code Playgroud)

列出所有形状

在“立即”窗口中列出活动工作表上的所有形状。(点击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
Run Code Online (Sandbox Code Playgroud)

删除所有形状

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

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
Run Code Online (Sandbox Code Playgroud)

更多信息:

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