Iteration through shapes in page not working

Started by Archangelos, August 18, 2021, 12:22:29 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Archangelos

Introduction
I am trying to make VBA remove all shapes that exist on particular layer. To remove the entire layer does not work for me, shapes that exist in more than one layer get retained.

The actual problem
I wrote a piece of code that iterates through all shapes. The primary function seems to work but there is a problem. The iteration does not work properly. Initially, it iterates though the 7 out of 10 shapes.

Deliverables
I have attached a (macro free) vsd file that has two pages. The shapes from the first page should get copied to second page. The shapes with the underlined text are the ones that are supposed to get deleted. The code follows.


Public Sub Layer_Example()

Dim NoOfLayers As Integer
Dim ShapeInPage As Shape
Dim CounterLayer As Integer
Dim CounterShapes As Integer

Dim OnomaLayer As String
Dim DelFlag As Boolean
Dim Selida As Page



Set Selida = ActiveDocument.Pages("run_code_here")
OnomaLayer = "0000_NON_LOCKABLE_OBJECTS"
CounterShapes = 0


For Each ShapeInPage In Selida.Shapes
    CounterShapes = CounterShapes + 1
    DelFlag = False
    NoOfLayers = ShapeInPage.LayerCount
    'MsgBox ShapeInPage & " exists in " & NoOfLayers & " layers"
    If NoOfLayers > 0 Then
      For CounterLayer = 1 To NoOfLayers
          'MsgBox ShapeInPage & ", " & ShapeInPage.Layer(CounterLayer)
          If ShapeInPage.Layer(CounterLayer) = OnomaLayer Then
             DelFlag = True
          End If
      Next CounterLayer
      If DelFlag = True Then
         ShapeInPage.Delete
      End If
   End If
Next ShapeInPage

MsgBox CounterShapes & " shapes were found in page"

End Sub

Surrogate

Try change For-Next iteration:
For i = Selida.Shapes.Count - 1 To 1 Step -1
    Set ShapeInPage = Selida.Shapes.Item(i)
...
Next

Paul Herber

It would be nice if there were a

For Each <var> in <range> Backwards

Electronic and Electrical engineering, business and software stencils for Visio -

https://www.paulherber.co.uk/

Surrogate

#3
Quote from: Paul Herber on August 18, 2021, 08:47:16 PM
For Each <var> in <range> Backwards
how you can make BackWards in this iteration ?

Paul Herber

You can't. I just suggested it would be nice.
Electronic and Electrical engineering, business and software stencils for Visio -

https://www.paulherber.co.uk/

wapperdude

Well that would be too simple and too easy.  Where's the fun in that???  The common perception doesn't realize that after each deletion there is a shape ID reassignment.  What's with that?!?.  Just execute the deletion loop and then re-sequence!!!  LOL.  Yeah.  It doesn't work that way.  😬😠   How many people get bit by that?  😱 😖  So...BACKWARDS-ho!.  😁😁😁

Too easy.
Visio 2019 Pro