Search code examples
vbapowerpointstatus

Powerpoint - VBA - Slide status


I hope you are doing well. I am a little stuck on a macro scripting, I would like to perform the following

  1. Once the macro is launch ; create a form rectangle with attributes (see below)
  2. If a rectangle already exist within the active slide the delete it.

Here is the little macro code written to insert the shape

Sub TBU()
Dim oSh As Shape
Set oSh = ActiveWindow.Selection.SlideRange.Shapes.AddShape(msoShapeRectangle, 902, 5, 47, 27)
With oSh
   With .TextFrame.TextRange
      .Text = "[TBU]"
       With .Font
        .name = "Arial"
        .Size = 12
        .Bold = msoFalse
        .Italic = msoFalse
        .Underline = msoFalse
        .Shadow = msoFalse
        .Emboss = msoFalse
        .BaselineOffset = 0
        .AutoRotateNumbers = msoFalse
        .Color = RGB(255, 0, 0)
    End With
    End With

    With oSh
        .Fill.Visible = msoTrue
        .Fill.ForeColor.RGB = RGB(255, 255, 0)
        .Fill.Solid
   End With
End With
End Sub

I tried to delete the shape within the active slide only if a rectangle with the same attributes already existed but got stuck on that.

Does anyone has an idea?

Kind regards, Naxos


Solution

  • I think the best way to find any shapes that you want to delete is to iterate over all the shapes in the current slide, and call a function that checks if the shape given matches your criteria.

    It would look something like the code below. Basically, any one condition not matching is sufficient to say that the shape shouldn't be deleted. Therefore the function starts off by assuming that the shape should be deleted until it finds any condition that indicates otherwise, at which point it changes the return value to false and ceases checking for the given shape.

    Dim i as Long
    Dim sh as Shape
    For i = ActiveWindow.View.Slide.Shapes.Count to 1 Step -1
        Set sh = ActiveWindow.View.Slide.Shapes(I)
        If ShouldBeDeleted(sh) Then
            sh.Delete
        End If
    Next
    
    '...
    
    Function ShouldBeDeleted(sh as Shape) as Boolean
        ShouldBeDeleted = True
    
        'Repeat this IF structure for each criteria.
        If sh.Fill.Visible <> msoTrue Then
             ShouldBeDeleted = False
             Exit Function
        End If
    
        If Not sh.HasTextFrame Then
             ShouldBeDeleted = False
             Exit Function
        End If
    
    
        '... keep repeating these if structures.
    
    End Function