简体   繁体   中英

Hiding Rows Based on Value of First and Last Cell

I have a workbook that has a number of sheets that represent items, and these sheets have numerous options in them to mark attributes of these items. There is also a central sheet that summarizes the items' attributes.

For examples sake lets say we have 2 sheets, one called Cat and one called Dog. If you filled in the relevant options it would appear in the summary sheet like so (if you can imagine each line being a row in Excel):


Cat


Name: Squiggles


Colour: Black


Legs: 4


Dog


Name: Woofers


Colour: White


Legs: 4


At the moment you can use an 'Item Select' sheet with some tickboxes on to select which items appear in the final summary. For the above example both Cat and Dog would be ticked, if one wasn't it wouldn't appear in the final summary.

This happens at the moment by hiding the exact rows that the Cat summary would appear on. This means that if you add any other rows above that, the VBA code wouldn't change and it would hide the wrong rows.

If CatCheckBox.Value = True Then
    'Unhide the rows that the Cat summary is on
    Sheets("Final Summary").Range("A3:A32").EntireRow.Hidden = False
Else
    'Hide the rows that the Cat summary is on
    Sheets("Final Summary").Range("A3:A32").EntireRow.Hidden = True
End If

What I would like to happen is for the VBA code to hide the Cat summary dynamically. The idea I had in mind would be to find the value 'Cat' in the sheet and another value say 'EndCat' and hide them rows and the ones in between. How could I go about this?

Look into named ranges . You can name ranges of cells (use Formulas-->Name Manager)

For example you could: name rows 2 to 5 as CAT name rows 6 to 9 as DOG name rows 10 to 13 as COW name rows 14 to 17 as HAMSTER

Now any inserts on row 1 would force the range to be renumbered automatically. Lets say you insert 5 rows before row 2. CAT is now (automatically) row 7 to 10, DOG is 11 to 14.

You can refer to these in code with

Sheets("Final Summary").Range("CAT").EntireRow.hidden = false 

Be aware, however that unprotected ranges of cells are at risk. You can insert a Row in the middle of these above ranges and it would expand the range. eg If CAT is row 2 to 5, inserting a row at row 3 would make the CAT range now 2 to 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM