Excel listing named range in a worksheet and get the value

后端 未结 2 386
臣服心动
臣服心动 2021-01-20 22:14

How to obtain a list of named range exist in a specific worksheet that start with particular string (for example all named range that start with total) and grab the value? I

2条回答
  •  野性不改
    2021-01-20 22:45

    Here is some code that checks if a Defined Name starts with a string and refers to a range within the used range of a given worksheet and workbook.

    Option Explicit
    Option Compare Text
    Sub FindNames()
        Dim oNM As Name
        Dim oSht As Worksheet
        Dim strStartString As String
    
        strStartString = "Total"
        Set oSht = Worksheets("TestSheet")
    
        For Each oNM In ActiveWorkbook.Names
            If oNM.Name Like strStartString & "*" Then
                If IsNameRefertoSheet(oSht, oNM) Then
    
                    MsgBox oNM.Name
                End If
            End If
        Next oNM
    End Sub
    
    Function IsNameRefertoSheet(oSht As Worksheet, oNM As Name) As Boolean
        Dim oSheetRange As Range
    
        IsNameRefertoSheet = False
        On Error GoTo GoExit
    
        If Not oSht Is Nothing Then
            If Range(oNM.Name).Parent.Name = oSht.Name And _
               Range(oNM.Name).Parent.Parent.Name = oSht.Parent.Name Then
                Set oSheetRange = oSht.Range("A1").Resize(oSht.UsedRange.Row + oSht.UsedRange.Rows.Count - 1, oSht.UsedRange.Column + oSht.UsedRange.Columns.Count - 1)
                If Not Intersect(Range(oNM.Name), oSheetRange) Is Nothing Then IsNameRefertoSheet = True
                Set oSheetRange = Nothing
            End If
        End If
    
        Exit Function
    GoExit:
    End Function
    

提交回复
热议问题