I have two shapes selected in VBA for powerpoint 2010, how do I create some sort of data structure out of them

StackOverflow https://stackoverflow.com/questions/9051822

Question

I am trying to create a memory game similar to the one here: http://www.mathsisfun.com/games/memory/index.html. I am approaching it like this:

The user selects two shapes and then starts a macro named associateShapes(), In associateShapes I use a Class Module named ShapeAssociation, in it I have two properties shape1Name and shape2Name, where the pair represents an association between those the shapes of those names.

So when I try to test ShapeAssociation, I use this module:

Global shapeAssociations() As ShapeAssociation
Global shapeAssoc As New ShapeAssociation
    Public Sub Test()
        ReDim shapeAssociations(0)
        shapeAssoc.shape1Name = ActiveWindow.Selection.ShapeRange(1).Name
        shapeAssoc.shape2Name = ActiveWindow.Selection.ShapeRange(2).Name

        Set shapeAssociations(0) = shapeAssoc
        MsgBox shapeAssociations(0).shape1Name
    End Sub

However, the Message Box I end up seeing is empty, possibly indicating that the shapeAssoc variable hasn't been initialized. I have tried several other approaches for creating a data structure of pairs of shapes in VBA, from a multiple dimension array of shapes to this approach. All these attempts bring their own error messages, be it compile time messages or run time messages. So my question to you is, how do I create a data structure in VBA that represents a pair of Shapes?

Was it helpful?

Solution

Since we can't see what's going on in your class module, I rewrote it a bit to use an array of UDTs instead. It works like so:

Public Type ShapeAssociation
    shape1Name As String
    shape2Name As String
End Type

Dim shapeAssociations() As ShapeAssociation

Public Sub Test()

    ReDim shapeAssociations(0)

    With shapeAssociations(0)
        .shape1Name = ActiveWindow.Selection.ShapeRange(1).Name
        .shape2Name = ActiveWindow.Selection.ShapeRange(2).Name
    End With

    MsgBox shapeAssociations(0).shape1Name & vbCrLf & shapeAssociations(0).shape2Name

End Sub

You'd want to verify that the user's actually selected at least two shapes (Selection.ShapeRange.Count), and only two shapes.

Also, do you plan to have the user play the game in Normal view or in SlideShow view? If the latter, none of this will work; you can't select anything in slideshow view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top