0

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 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks very much, I'll give this a go
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?
@JamesMcS You need to test for them......after all, PrintArea is a valid group of cells, just like any other user-defined Named Range !
@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/…
0

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

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.
Thanks very much! I'll give this a go
@JamesMcS please give it an up. I am just starting :-) thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.