Home » excel » vba – cell value to change when hiding/unhiding specific rows in excel?

vba – cell value to change when hiding/unhiding specific rows in excel?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am currently working with an excel sheet where I have grouped row 1-17 and have written a cell value in cell B18. I am wondering if there is a way to change the value in B18 when I click on the +/- sign when expanding/collapsing the rows.

For example: I want the cell value in B18 to be “Yes” when I click on the plus sign, and the value to be “No” when I click on the minus sign. Is there any way to do this?

Kinds regards,
Sandra

How to&Answers:

Hello and welcome to Stack Overflow!

In general, you should always provide some proof (code) of your previous attempts, not only it helps us to understand better what you’re trying to achieve, but also because of core principle behind this website is to help people with their code, not to do the coding for them!


Either way, I’ll go out of my way and make an exception, given this is your first question and what you’re trying to achieve is fairly easy to do.

Though my answers depends on what exactly you’re trying to achieve though as it’s not clear from your intial question.

  1. If all the rows (1:17) are hidden

    Private Sub check_hidden_area()
      If Rows("1:17").EntireRow.Hidden = True Then
        Range("B18") = True
      Else
        Range("B18") = False
      End If 
    End Sub
    
  2. If at least 1 row in (1:17) is hidden:

    Private Sub check_hidden_area()
    Range("B18") = False
      For i = 1 To 17
         If Rows(i).EntireRow.Hidden = True Then
           Range("B18") = True
           Exit For
         End If
      Next i
    End Sub
    

PS/Note: The procedures listed do work, but as of now they don’t auto-trigger (start) unless you launch them manually. Unfortunately it is impossible to trigger the code on the “+/-” buttons.

  1. Closest thing you can get to this being correct is to fire the macro on every worksheet change, this will however clog down the speed of your program and hog your CPU/Memory, especially if working with bigger data ranges

    Private Sub Worksheet_Change (ByVal Target as Range)
       '...
       Call check_hidden_area
    End Sub
    
  2. Alternatively just create a button (or something..) and call the procedure on _Click trigger, eg.

    Private Sub CommandButton1_Click 
       Call check_hidden_area
    End Sub