简体   繁体   中英

Pass all the Range Names in an Excel Workbook to an Array

I would like to pass the existing names in a Workbook to an Array and Redim the array to UBound limit, but I cannot even get to first base of returning the names.

I am preparing a very basic Monte Carlo simulation and want to use the array for inputs and outputs as we'll as the basis to create a Histogtram and Cumualtive charts.

Sub RangeCheck_()
Dim N As Name
For Each N In ActiveSheet.Names
MsgBox N
Next N
End Sub

Even this very basic routine does not work on a sheet with 40 names defined. Appreciate I could save the list of names with a simple Range("X").listnames and then feed that to an array but its very clumsy and I am hoping someone can suggest a better solution. I am doing this in Excel 2011 in case that makes a difference.

Thanks you

Peter

Consider:

Sub qwerty()
    Dim n As Name
    For Each n In ActiveWorkbook.Names
        MsgBox n.Name
    Next n

    nCount = ActiveWorkbook.Names.Count
    Dim ary
    ReDim ary(1 To nCount) As String

    For i = 1 To nCount
        ary(i) = ActiveWorkbook.Names(i)
    Next i
End Sub

Try this. It's a one-dimensional array, so you'll need additional code if you want a 2D variant:

Option Explicit

Public Function AllTheWorkbookNames(Optional myWorkbook As Excel.Workbook) As Variant
' Return a one-dimensional array of all the names in a Workbook
' Uses the current workbook if the myWorkbook parameter is omitted


Dim xlName   As Excel.Name
Dim xlSheet  As Excel.Worksheet
Dim arrNames As Variant
Dim strNames As String


If myWorkbook Is Nothing Then
    Set myWorkbook = ThisWorkbook
End If


' join up the workbook-level names in a string, separated by a character
' (vbNullChar) that can't be used in in range names and worksheet names:
For Each xlName In myWorkbook.Names

    strNames = strNames & xlName.Name & Chr(0)

Next xlName

' Join up the worksheet-level names. Chr(34) is just the character for a
' single quote, we're using it because "'" is bad for code readability:
For Each xlSheet In myWorkbook.Worksheets

    For Each xlName In myWorkbook.Names

        strNames = strNames & Chr(34) & xlSheet.Name & Chr(34) & "!" & xlName.Name & Chr(0)

    Next xlName

Next xlSheet


' Trim the trailing delimiter:
strNames = Left(strNames, Len(strNames) - 1)

' Use the 'split' function to turn this string into an array:
arrNames = Split(strNames, Chr(0))

AllTheWorkbookNames = arrNames


Erase arrNames

End Function

The additional code for a 2D array is:

Dim i As Long

ReDim arr2D(LBound(arrNames) To LBound(arrNames), 0 To 0)
For i = LBound(arrNames) To LBound(arrNames)
    arr2D(i, 0) = arrNames(i)
Next

AllTheWorkbookNames = arr2D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM