ReferesToRange给出运行时错误'91':

嗨,我不断收到“variables或块variables未设置”为下面的代码循环的行。 谁能告诉我我要去哪里? 谢谢

Public Sub TestFind() Set wsNew = Worksheets.Add(after:=Worksheets(Worksheets.Count)) wsNew.Range(wsNew.Cells(1, 1), wsNew.Cells(1, 17)).Value _ = Array("ReturnId", "GridName", "Item", "TabName", "AltFldName", "FieldPos", "Reference", "Type", _ "SortPos", "FieldSize", "CalcField", "CellDesc", "DoNotExport", "SortStrategy", "Threshold", "IsInnerGridCell", "ReportLine") Dim Nm As Name Dim rng As Range Dim wb As Workbook Set wb = ThisWorkbook For Each Nm In ThisWorkbook.Names rng = Nm.RefersToRange.Value Next End Sub 

代码中有两个问题:

1-并不是所有的名字都必定是指定的范围。 例如,它们可以指常量。 所以你需要添加一些检查之前,假设名称实际上是一个范围。

2-将范围对象分配给命名范围,则需要使用Set

尝试这个:

 Dim Nm As Name, rng As Range For Each Nm In ThisWorkbook.Names Debug.Print Nm.Name On Error Resume Next Set rng = Nm.RefersToRange ' <-- Use Set to assign object references If Err.Number <> 0 Then GoTo NextNm ' <-- This name does not refer to a named range On Error GoTo 0 Debug.Print rng.Address ' ... Do whatever you want with the named range NextNm: On Error GoTo 0 Next Nm 

调整和评论。

 Option Explicit Sub wqewtr() Dim Nm As Name Dim rng As Range Dim var As Variant '<~~ for numbers, dates and/or text Dim wb As Workbook Set wb = ThisWorkbook For Each Nm In ThisWorkbook.Names Debug.Print Nm.Name 'nm could a 'special internal name' that starts with an underscore 'skip over these If Left(Nm.Name, 1) <> "_" Then 'show the address of the defined name range - could be more than one cell Debug.Print Nm.RefersToRange.Address 'do not try to assign value to a range object unless that range already has been asinged a cell or cells 'rng = Nm.RefersToRange.Value 'Debug.Print rng 'this fails if Nm is more than a single cell 'var = Nm.RefersToRange.Value 'Debug.Print var 'this guarantees one cell var = Nm.RefersToRange.Cells(1, 1).Value Debug.Print var End If Next End Sub 

尝试下面的报告。 你没有包括你的一些编码,我假设…

 Dim Nm As Name Dim rng As Range Dim wb As Workbook Set wb = ThisWorkbook For Each Nm In ThisWorkbook.Names rng = Nm.RefersToRange.Value Next