Search code examples
vbams-officevisio

Visio VBA Get Shape from Selection


I need a reference to a selected (via mouse click, it only needs to be one selection) shape in Visio. However the shape might be in a group. I cant seem to get it to work when I select a shape in a group, the shp Object remains empty.

Sub selectTest()
    Dim sel As Visio.Selection
    Set sel = ActiveWindow.Selection
    Dim shp As Visio.Shape
    Set shp = sel.PrimaryItem

    If Not shp Is Nothing Then
        MsgBox "It worked"
    Else
        MsgBox "No shape in sel"
    End If        
End Sub

When the "Top-Level" Group is selected, it works. When a shape inside the group, which might as well be a group itself, is selected, it doesn't. When a shape which is not in a group is selected, it works again.

Context: I want to fire custom VBA code from the context menu. When you right click the shape, it is selected automatically.

How can I get a reference to a shape when it is in a group?

EDIT: To clarify further: Shapes inside my Document all have corresponding database entries. I want to (via XML) add a custom Delete button to the context menu (that works), this should call a deletemethod that gets the shape on which the method was called as a parameter so it can search for the corresponding DB entry and delete that (as well as the entries of any subshapes if the selected shape is a group) before the shape (and all of its subshapes) is deleted with shape.delete


Solution

  • Use Selection.IterationMode property to include sub-selected shapes in the selection

    Set sel = ActiveWindow.Selection
    sel.IterationMode = 0
    Set shp = sel.PrimaryItem