Looping through all named ranges in excel VBA in current active sheet

前端 未结 2 784
一个人的身影
一个人的身影 2020-12-19 16:08

I am looking to loop through all named ranges found in a activeworksheet and then do something to them. I\'ve used the code below but it does not seem to produc

2条回答
  •  执笔经年
    2020-12-19 16:28

    This macro will loop through all named ranges in your workbook. It takes the comments above into consideration and shows how you can do things with specific ranges.

    Sub nameLoop()
    Dim nm
    Dim wb As Workbook
    Set wb = ActiveWorkbook
    For Each nm In wb.Names
        If InStr(1, nm.Name, "data") Then
            ' Do stuff with the named range.
            Debug.Print nm.Name
        End If
    Next nm
    End Sub
    

    Note, using InStr() will find "data" anywhere in the name. So if you have data1, datas1, and myData1, it'll run the "do stuff here" code for all of those. If you just want ranges starting with data, then change the InStr() line to: If Left(nm.Name,4) = "data" Then

    Edit: You can couple this with the If nm.RefersToRange.Parent.Name = ActiveSheet.Name line suggested by @user1274820 below. (Just make the If statement include an And operator).

提交回复
热议问题