Search code examples
excelvbaif-statement

Show one group image out of three based on cell input


I have the rotation working, it's just the hiding and unhiding of the three images that will not work. I have an "if" "else" loop for the three values that are autopopulated by a vlookup for either 90, 135, or 180 degrees. When I run the code, it seems to just pick one of the two images I tell to hide. What is really strange to me is it is not always the first group that gets hidden, sometimes it is the second. I don't understand how I could change the code to make it hide both images for each "if" scenario.

This is my code so far, only the if-else loop for hiding the groups is not working:

Sub Macro1()
    
    response = MsgBox("Are you sure the SP# is correct?", vbYesNo, "Angle Confirmation")
    If response = vbNo Then
        Exit Sub
    End If
        Dim x As Integer
        x = Range("D23").Value
        ActiveSheet.Shapes.Range(Array("Group 2")).Select
        Selection.ShapeRange.IncrementRotation x
        

        If Range("B24").Value = 90 Then
            ActiveSheet.Shapes("Group 13").Visible = False: ActiveSheet.Shapes("Group 25").Visible = False
        ElseIf Range("B24").Value = 135 Then
            ActiveSheet.Shapes("Group 5").Visible = False: ActiveSheet.Shapes("Group 25").Visible = False
        ElseIf Range("B24").Value = 180 Then
            ActiveSheet.Shapes("Group 5").Visible = False: ActiveSheet.Shapes("Group 13").Visible = False
        End If
End Sub

Solution

  • The problem with your code is that it doesn't unhide previously hidden shapes although B24 value would be correct. That's why your result looks "weird".

    Try this code to hide and unhide the shapes based on the B24 value. It first configures the visibility-value per shape. And then sets the visibility per each shape based on the value of B24. The advantage of the "configuration": if there are more groups you just add them to the array.

    Public Sub hideGroupsBasedOnB24()
    
    Dim arrConfig(2, 1) As Variant
    'first dimension: group name, second dimension visible value
    arrConfig(0, 0) = "Group 5": arrConfig(0, 1) = 90
    arrConfig(1, 0) = "Group 13": arrConfig(1, 1) = 135
    arrConfig(2, 0) = "Group 25": arrConfig(2, 1) = 180
    
    Dim i As Long
    With ActiveSheet
        For i = 0 To UBound(arrConfig, 1)
            .Shapes(arrConfig(i, 0)).Visible = .Range("B24").Value = arrConfig(i, 1)
        Next
    End With
    
    End Sub