Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set range and define named range in VBA

Tags:

excel

vba

I am trying to define a named range (with Workbook scope) in VBA based on certain inputs to help figure out the cells that should be included in the range. To make it really simple, I have tried the following two with the errors indicated below. A, B, X, Y are found from some calculations

rName = <some string that decides the name>
Set TempRng = .Range(.Cells(A,B), .Cells(X,Y))
ActiveWorkbook.Names.Add Name:=rName, RefersTo:=Worksheets("Sheet1").TempRng

This gives me an "object or method not supported" error or something like that, on the Set TempRng line.

rName = <string ...>
Set TempRng = Worksheets("Sheet1").Range(Cells(A,B), Cells(X,Y))
ActiveWorkbook.Names.Add Name:=rName, RefersTo:= <blah blah...>

This gives me an "application defined or object defined error" on the same line.

Can you please help me find the correct way to define this range?

like image 567
Jabberwocky Avatar asked Sep 17 '25 16:09

Jabberwocky


2 Answers

I think this is a bit more direct.

TempRng.Name = rname

Or you can even directly assign the name without using variable.

TempRng.Name = "myrangename"

The scope of the name is Workbook just in case that is critical in your needs. HTH.

like image 175
L42 Avatar answered Sep 19 '25 08:09

L42


Use:

Refersto:="=" & TempRng.Address

Or more directly (as L42 says)

TempRng.Name = stName

To set your range make sure you've included "With" before you start "."ing things

With wsWhatever
    Set TempRng = .Range(.Cells(A,B), .Cells(X,Y))
end with
like image 36
Simon Avatar answered Sep 19 '25 07:09

Simon