Share via

Automatically update row references in VBA code when rows are updated in Excel?

Anonymous
2021-09-06T20:48:55+00:00

Hi,

I have some VBA code to hide some rows that looks like this:

If Range("$B$4") .Value = "Test" Then Rows("37:50") .Hidden = True

If Range("$B$4") .Value = "Test" Then Rows("65") .Hidden = True

and so on...

If I add some new rows in the Excel file, however, (e.g. say I add 5 rows in the Excel file after row 20) then the vba code does not hide the correct rows anymore. How can I revise this code to properly hide the desired rows after adding new rows to the Excel file?

Thnx for any help!

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

5 answers

Sort by: Most helpful
  1. HansV 462.6K Reputation points
    2021-09-07T09:27:01+00:00

    Use

    If Range("$B$4").Value = "Test" Then  
        Range("RowRange1").EntireRow.Hidden = True  
        Range("RowRange2").EntireRow.Hidden = True  
    End If
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments
  2. HansV 462.6K Reputation points
    2021-09-06T20:57:08+00:00

    I'd use named ranges.

    Select rows 37:50, click in the name box on the left hand side of the formula bar, enter a name, for example RowRange1, and press Enter.

    Select row 65 and similarly name it for example RowRange2.

    You can then use

    If Range("$B$4") .Value = "Test" Then Range("RowRange1") .Hidden = True

    If Range("$B$4") .Value = "Test" Then Range("RowRange2") .Hidden = True

    Excel will automatically update the definition of the named ranges as you insert or delete rows above them.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments
  3. Anonymous
    2021-09-07T14:29:17+00:00

    TY. This worked!

    Was this answer helpful?

    0 comments No comments
  4. Anonymous
    2021-09-06T22:11:10+00:00

    Hi. I tried what you suggested on one row to see if it would work.

    Selected row 37 in excel and typed RowRange1 in the name box.

    Changed vba code to If Range("$B$4") .Value = "Test" Then Range("RowRange1") .Hidden = True

    Got error message below:

    Was this answer helpful?

    0 comments No comments
  5. Anonymous
    2021-09-06T21:51:26+00:00

    Thanks! I'll give it a shot!

    Was this answer helpful?

    0 comments No comments