Home » excel » excel vba – Hide charts from cell value

excel vba – Hide charts from cell value

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a cell that contains a drop down list of values Chart 1-4
I am attempting to run a rather simple VBA script to only show the chart selected but it is not working and I am not sure why.

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1")) Is Nothing Then
    If Range("A1").Value = "Chart 1" Then
        ActiveSheet.ChartObjects("Chart 1").Visible = True
        ActiveSheet.ChartObjects("Chart 2").Visible = False
        ActiveSheet.ChartObjects("Chart 3").Visible = False
        ActiveSheet.ChartObjects("Chart 4").Visible = False
    Else
        ActiveSheet.ChartObjects("Chart 1").Visible = False
        ActiveSheet.ChartObjects("Chart 2").Visible = False
        ActiveSheet.ChartObjects("Chart 3").Visible = False
        ActiveSheet.ChartObjects("Chart 4").Visible = False
    End If
End If
End Sub

I get an error:

error

The beginning statement is mean so that only the code will run if the value in cell A1 is changed. Also, maybe I should use a with statement?

How to&Answers:

I’m writing this as an answer as per Jon Peltier’s comment.

As SJR pointed out, I’m pretty sure it must be some code/comment or otherwise outside your Subroutines, your code as it stands seems correct (as long as you have Charts named as they are on your code)…

Answer:

Try creating a procedure in a module that works your chart logic. For example:

In the worksheet module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1")) Is Nothing Then
        SetChartVisibility ActiveSheet
    End If
End Sub

Then in a separate module:

Public Sub SetChartVisibility(ByRef ws As Worksheet)
    With ws
        If .Range("A1").Value = "Chart 1" Then
            .ChartObjects("Chart 1").Visible = True
            .ChartObjects("Chart 2").Visible = False
            .ChartObjects("Chart 3").Visible = False
            .ChartObjects("Chart 4").Visible = False
        Else
            .ChartObjects("Chart 1").Visible = False
            .ChartObjects("Chart 2").Visible = False
            .ChartObjects("Chart 3").Visible = False
            .ChartObjects("Chart 4").Visible = False
        End If
    End With
End Sub