VBA Help - Dynamically Update Named Range to Lastrow

Johnny Thunder

Well-known Member
Joined
Apr 9, 2010
Messages
693
Office Version
  1. 2016
Platform
  1. MacOS
Hi Guys, working on a script to dynamically update a named range for my data to the last row when a report is ran and hitting a roadblock with my code.

I am getting an error on the code, most likely because the syntax is wrong so I was hoping someone may know how to do this.

I am using the Usedrange line to find the last active row in my workbook but its not working. My data currently goes to row 5000.

Any help is appreciated


Code:
Sub UpdateRanges()


Dim sht As Worksheet
Dim wb As Workbook
Dim nr As Name
Dim lastR As Long


lastR = sht.UsedRange.SpecialCells(xlCellTypeLastCell).Row
    
With ActiveWorkbook.Names("Data1")
        .Name = "Data1"
        .RefersTo = "=Query1!$A$14:$AC$" & lastR & """"
        
    End With


End Sub
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
If you are using Column A then try

LastR = Cells(Rows.count, 1).end(xlup).row (adjust the 1 to whichever column number you are checking)
 
Upvote 0
Also,which sheet is sht? if it is the active sheet then say activesheet.cells(rows.count,1.end(xlup).row
 
Upvote 0
Worked like a charm!

New Code:
Code:
Sub UpdateRanges()


Dim sht As Worksheet
Dim wb As Workbook
Dim nr As Name
Dim lastR As Long


Set sht = Sheets("Query1")




lastR = sht.Cells(Rows.Count, 2).End(xlUp).Row
    
With ActiveWorkbook.Names("Data1")
        .Name = "Data1"
        .RefersTo = "=Query1!$A$14:$AC$" & lastR & ""
        
    End With


End Sub



Also,which sheet is sht? if it is the active sheet then say activesheet.cells(rows.count,1.end(xlup).row
 
Upvote 0

Forum statistics

Threads
1,223,886
Messages
6,175,193
Members
452,616
Latest member
intern444

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top