Assign a Name to a Range in VBA

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I would like to be able to assign a name to a range in VBA. For example:

Sub mac2()
Dim r As Range
Set r = Cells(1, 1)
For i = 2 To 10
If Not IsEmpty(Cells(i, i).Value) Then
Set r = Union(r, Cells(i, i))
End If
Next
r.Select

ActiveWorkbook.Names.Add Name:="diagonal", RefersToR1C1:= ?????????

End Sub


By Naming a range I can make it available to worksheet functions.
 
Sub mac2()
Dim r As Range
Dim i As Integer

Set r = Cells(1, 1)
For i = 2 To 10
If Not IsEmpty(Cells(i, i).Value) Then
Set r = Union(r, Cells(i, i))
End If
Next
r.Select

ActiveWorkbook.Names.Add Name:="diagonal", RefersTo:=r

End Sub
 
Hello
ActiveWorkbook.Names.Add Name:="diagonal", RefersToR1C1:=r.Address

HTH
Cordially
Pascal
 
Thank you for your help. Your solution works perfectly for small ranges:

For i=2 to 10 worked
For i=2 to 224 worked
For i=1 to 225 threw a "1004" exception.

Is there a limit to the number of cells in a named range??
 
My guess: you're hitting a limit based on the number of characters in the
string that represents the addresses for all the cells.
 
Maybe just:

if r is nothing then
'error message here
else
r.name = "Diagonal"
end if
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top