Home » excel » excel – hide graph based on cell value

excel – hide graph based on cell value

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am new to Excel VBA, and I am trying to solve this problem with VBA code.

Basically, my sheet has 12 charts and 12 tables. At any given time, only one table will get data and only that graph should be seen. The other 11 graphs should be hidden.

I have tried this

Sub getchart()

    If Range("C1") = Vub Then
      ActiveSheet.ChartObjects("Chart_33").Visible = True
    Else
      ActiveSheet.ChartObjects("Chart_33").Visible = False
    End If

End Sub

enter image description here

enter image description here

How to&Answers:

If you need the graph to change from visible to not visible as you change the value of the cell you need to use an event.

e.g.

Private Sub Worksheet_change(ByVal Target As Range)

If Target.Address = "$C$1" Then
  if target.value = "vub" then
    ActiveSheet.ChartObjects("Chart_33").Visible = True
  Else
    ActiveSheet.ChartObjects("Chart_33").Visible = False
  end if
End If

End Sub

This code should be inserted in the sheet module for the sheet in which your graph is placed. The sheet module can be found in the sidebar.

Answer:

You can cut down @MrML’s answer to:

Private Sub Worksheet_change(ByVal Target As Range)
    If Target.Address = "$C$1" Then
        ActiveSheet.ChartObjects("Chart_33").Visible = (target = "vub")
    End If
End Sub