Existence of shapes in Powerpoint

前端 未结 2 1266
醉话见心
醉话见心 2021-01-24 11:04

I would like to build a condition on a command button on a Macro enabled powerpoint presentation. If the shape exists then I would like it deleted, otherwise the button should p

相关标签:
2条回答
  • 2021-01-24 11:43

    Some of the other suggestions will work but in general, it's bad practice to rely on selection unless absolutely necessary. Instead, you could call a slightly different function:

    Function ShapeExists(ByVal oSl as Slide, ByVal ShapeName as String) as Boolean
       Dim oSh as Shape
       For Each oSh in oSl.Shapes
         If oSh.Name = ShapeName Then
            ShapeExists = True
            Exit Function
         End If
       Next ' Shape
       ' No shape here, so though it's not strictly necessary:
       ShapeExists = False
    End Function
    

    You could also modify this to return a reference to the shape if found or nothing if not.

    If you prefer not to use early Exit Functions, there are easy ways to write around that.

    0 讨论(0)
  • 2021-01-24 11:48

    As @davidmneedham gives in the link in the comments (@TimWilliams answer), you can use a construct similar to as follows:

    Option Explicit
    
    Sub test()
    
    Dim shp As Shape
    Dim myshapeName As String
    myshapeName = "Picture"
    Dim sl As Slide
    
    Set sl = ActivePresentation.Slides(1)
    
     If shapePresent(sl, myshapeName) Then
    
         sl.Shapes(myshapeName).Delete
    
     Else
    
        MsgBox myshapeName & " not present"
    
     End If
    
    End Sub
    
    
    Private Function shapePresent(ByVal sl As Slide, ByVal myshapeName As String) As Boolean
    
       On Error GoTo errhand
    
       sl.Shapes(myshapeName).Select
    
       shapePresent = True
       Exit Function
    
    errhand:
    
    shapePresent = False
    Err.Clear
    
    End Function
    

    Using the same format as that answer:

    Private Function shapePresent(ByVal sl As Slide, ByVal myshapeName As String) As Boolean
    
        Dim myShape As Shape
    
        On Error Resume Next
    
        Set myShape = sl.Shapes(myshapeName)
    
        On Error GoTo 0
    
        shapePresent = Not myShape Is Nothing
    
    End Function
    
    0 讨论(0)
提交回复
热议问题