I'm trying to figure out how I can get the names of ranges in a given worksheet into an array. I've got as far as the listnames function but that seems to list them all in one go. Any ideas?
2 Answers
Something like:
Sub listum()
Dim ary(1 To 3) As String
With ActiveWorkbook
If .Names.Count > 0 Then
For i = 1 To .Names.Count
MsgBox (i & " " & .Names(i).Name & " " & Range(.Names(i)).Address)
ary(i) = .Names(i).Name
Next
End If
End With
End Sub
will display them and put them into an array.
Size the array to suit your needs.
Insure that there are no non-Range Names in the workbook.
4 Comments
JamesMcS
Thanks very much, I'll give this a go
JamesMcS
Have just tried this, I din't know about "names" - but it's taking the workbook name, print area etc into the array, which is causing problems down the line. Any thoughts?
Gary's Student
@JamesMcS You need to test for them......after all,
PrintArea is a valid group of cells, just like any other user-defined Named Range !Christopher Oezbek
@JamesMcS: Did you find any way to exclude them well? I am building a small template exporter for word using Named Ranges and it would be good to exclude built-in fields github.com/coezbek/…
My version is I used dynamic array:
Sub TestNamedRange()
Dim i As Long
Dim intCount As Long
Dim NameArray() As String
'count number of named ranges
intCount = ThisWorkbook.Names.Count
ReDim NameArray(intCount) 'for dynamic number of named ranges
'assign all names to each array element
For i = 1 To intCount
NameArray(i) = ThisWorkbook.Names(i).Name 'remove .Name if you want address range only
Next
'check array elements
For Each ele In NameArray
Debug.Print ele
Next
'manipulate your array here
End Sub
3 Comments
jkpieterse
Though rare I have seen workbooks with more than 32767 names so best to use a Long rather than an integer. Since use of an Integer do not offer any advantage over Long I'd advise to always use Long to avoid problems like this.
JamesMcS
Thanks very much! I'll give this a go
Wils Mils
@JamesMcS please give it an up. I am just starting :-) thank you.