Loop through named range list

旧街凉风 提交于 2020-01-06 06:24:10

问题


I found a lot of examples but it's not working in my case and I don't know why. Very basic code:

Sub Test()
Dim namCur As Name

For Each namCur In ActiveSheet.Names
MsgBox "Name: " & namCur.Name & ", Refers To: " & namCur.RefersTo
Next namCur
End Sub

And I have the same issue when I use Worksheets("Assumptions").Names

When I watch ActiveSheet.Name, this is correct I get "Assumptions", you can see on the picture below the list of named ranges. But I never get the MsgBox and the For loop goes directly to the end. Edit: Very important, I need to loop only this sheet's named ranges, not the whole workbook Any idea?

I use Excel 2016


回答1:


Your solution will only list Names that have a scope set to only the ActiveSheet.

Change this

For Each namCur In ActiveSheet.Names

To this

For Each namCur In ThisWorkBook.Names

to list all names in the Workbook. You can then check the RefersTo address to check if it applies to the ActiveSheet.

Sub Test()

Dim namCur As Name
Dim TargetSheetName As String

TargetSheetName = "Assumptions"

For Each namCur In ThisWorkbook.Names

    If Range(namCur.RefersTo).Parent.Name = TargetSheetName Then MsgBox "Name: " & namCur.Name & ", Refers To: " & namCur.RefersTo

Next namCur

End Sub


来源:https://stackoverflow.com/questions/50984778/loop-through-named-range-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!