Search code examples
vbacomboboxpowerpointshapes

Making a ComboBox Selection Control Visibility/Non Visibility of Shapes Powerpoint VBA


I have a simple ComboBox in a slide with values added as follows:

0 = 2018 Pinot Noir
1 = 2019 Pinot Noir
2 = 2020 Pinot Noir

I now want the user selection to control whether the image (shape) in Powerpoint is visible or not. So I thought a simple case statement on the ComboBox1_Change event would be sufficient. However, I then realised I would probably have to assign the above values to the name of the images in the slide. These names are identical to the ComboBox values.

I've done this before but I am sure I'm missing an object of Powerpoint to achieve this. So far the code is:

Option Explicit

Private Sub ComboBox1_GotFocus()
    If ComboBox1.ListCount = 0 Then AddDropDownItems
End Sub

Sub AddDropDownItems()
    ComboBox1.AddItem "2018 Pinot Noir"
    ComboBox1.AddItem "2019 Pinot Noir"
    ComboBox1.AddItem "2020 Pinot Noir"
    ComboBox1.ListRows = 3
    'ComboBox1.Clear
End Sub

Sub ComboBox1_Change()

    Dim imgPinot As Shape
    Dim imgPinot2 As Shape
    Dim imgPinot3 As Shape


    Select Case ComboBox1.Value
        Case 0
            imgPinot.Visible = True
            imgPinot2.Visible = False
            imgPinot3.Visible = False
        Case 1
            imgPinot.Visible = False
            imgPinot2.Visible = True
            imgPinot3.Visible = False
        Case 2
            imgPinot.Visible = False
            imgPinot2.Visible = False
            imgPinot3.Visible = True
    End Select
End Sub

The other thing I want to control is that once the user has finished the selection, the Index of the Combo Box is reset.

I feel a little foolish not being able to do this. Must be getting to old! Please assist if you can.


Solution

  • This should work if your image names match your combobox entries

    Option Explicit
    
    Private Sub ComboBox1_GotFocus()
        If ComboBox1.ListCount = 0 Then AddDropDownItems
    End Sub
    
    Sub AddDropDownItems()
        ComboBox1.AddItem "2018 Pinot Noir"
        ComboBox1.AddItem "2019 Pinot Noir"
        ComboBox1.AddItem "2020 Pinot Noir"
        ComboBox1.ListRows = 3
    End Sub
    
    Sub ComboBox1_Change()
        Dim sel, n As Long, cb As ComboBox, nm
        
        Set cb = Me.ComboBox1
        sel = cb.Value                         'selected item
        'loop over list 
        For n = 1 To cb.ListCount
            nm = cb.List(n - 1)                'list entry
            Me.Shapes(nm).Visible = (nm = sel) 'show only if entry matches selection
        Next n
    End Sub