How to make VBA change the range automatically in the code, when changing the range used to an other cell

Luis GE 21 Reputation points
2021-11-16T19:07:06.397+00:00

When I set this code for instance (view below) ,and in the excel I add a new row, then de range changes instead of G9 to G10 in one case.
For that reason the macro stop working because I have to change manually the range in VBA.

is there any way that this range is modified automatically in VBA when I change it in the excel adding a row o moving the actual range?

Range("G9").Select
ActiveSheet.Range("$B$21:$R$74").AutoFilter Field:=6, Criteria1:=Range("C14")
If Range("C14") = "" Then
ActiveSheet.Range("$B$22:$R$74").AutoFilter Field:=6
Office Mac
Office Mac
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Mac: A family of Apple personal computers that run the macOS operating system.
506 questions
{count} votes

Accepted answer
  1. Viorel 117.6K Reputation points
    2021-11-17T06:35:29.017+00:00

    If G9 is a special cell, maybe you should assign a distinct name. Right-click the G9 cell, select "Define name...", and enter a name. Then use the new name instead of "G9", for example: Range("SomeName").Select.

    Or maybe you mean that G9 should be always in the last row?

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Luis GE 21 Reputation points
    2021-11-17T16:50:04.567+00:00

    Thank @Viorel
    I think if I named the cell and I move it, it will work

    If I want the macro to update automatically, I have this code, only when putting the name of the cell as you indicate, it does not do any action, how would it be to update when a name is given to the cell?

    Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$C$4" Then  
        Call Filtros  
    End If     
    End Sub  
    

    I try this but it does not work

    Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "Name cell" Then
    Call Filtros
    End If
    End Sub


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.