Home > other >  Getting the number of shapes with in a layer on visio using VBA
Getting the number of shapes with in a layer on visio using VBA

Time:06-10

I am trying to create a macro in VBA with Visio, that would count the amount of shapes in a layer and report the number. Would anyone have any ideas or pointers on how to approach this?

I know how to report the number of shapes in a entire workbook but I'm needing to report the quantity in a layer to see if it even has items assigned to it. I thought something like Layers.count would work but I'm not sure if that's even the correct way.

CodePudding user response:

You can use the CreateSelection method on Page and then return the count from that.

For example:

Public Sub GetTheCount()
    Dim layerName As String
    Dim count As Integer
    
    layerName = "Flowchart"
    
    count = CountShapesOnLayer(ActivePage, layerName)
    Debug.Print "There are " & count & " shapes on layer " & layerName
End Sub


Public Function CountShapesOnLayer(ByRef vPag As Visio.Page, layerName As String) As Integer
    If Not vPag Is Nothing Then
        Dim vLayer As Visio.Layer
        Dim vSel As Visio.Selection
 
        Set vLayer = vPag.Layers.ItemU(layerName)
        Set vSel = vPag.CreateSelection(Visio.VisSelectionTypes.visSelTypeByLayer, _
                                    Visio.VisSelectMode.visSelModeSkipSuper, _
                                    vLayer)
        CountShapesOnLayer = vSel.count
    Else
        CountShapesOnLayer = 0
    End If
End Function

Note the SelectMode argument, which in the above will give you the top level shapes, but bear in mind that you may need to change this if you're dealing with sub-shapes (in a group).

  • Related