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

Select a hidden cell
Somehide hide payroll data in column G? Press F5. Type G1. Enter. Look in formula bar while you arrow down through G.
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,215,475
Messages
6,125,028
Members
449,205
Latest member
Eggy66

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