如何遍历Names集合并返回对象的大小?

时间:2019-04-03 15:44:45

标签: excel vba

我正在尝试遍历Names集合,每个符合特定大小(列)要求的Name都会调整大小(在另一个子目录中调用)。

当我尝试将返回的名称传递给Range时,出现以下错误。

  

“运行时错误'1004':对象'_Global'的方法'Range'失败。

Sub colCounts()
    Dim wb as Workbook
    Dim nm as Name
    Dim rng as Range
    Set wb = ActiveWorkbook

    For Each nm in wb.Names
        debug.print nm.Name ' verify loop returning as expected
        Set rng = Range(nm.Name) 'this line throws the error when added
        debug.print nm.Name & " " & rng.Columns.Count
    Next nm
End Sub

我还尝试过先将Name传递给字符串:

Dim str as String
.....
str = nm.Name
Set rng = Range(str)

1 个答案:

答案 0 :(得分:0)

Sub colCounts()

    Dim wb As Workbook
    Dim nm As Name
    Dim rng As range

    Set wb = ActiveWorkbook

   For Each nm In wb.Names

       Set rng = ThisWorkbook.Names(nm.Name).RefersToRange
       Debug.Print nm.Name & " " & rng.Columns.Count

    Next nm

End Sub