types不匹配,我已经在pipe理器中命名的范围

我希望有人能帮我弄清楚为什么我在这种情况下得到一个types不匹配。 我会期望范围variables“returnDetectionRange”和名称pipe理器中名为“returnChangeDetectionRange”的对象都是Rangetypes,但我得到一个错误。

Dim returnDetectionRange As Range Set returnDetectionRange = ActiveWorkbook.Names("returnChangeDetectionRange") 

在名称pipe理器中,returnChangeDetectionRange指的是使用偏移公式的dynamic范围:

 =OFFSET(Returns!$D:$D, 0, 'Market Value'!$E$2) 

感谢您花时间看我的问题!

你非常接近,但需要使用Name.RefersToRange属性:

 Set returnDetectionRange = ActiveWorkbook.Names("returnChangeDetectionRange").RefersToRange 

ActiveWorkbook.Names集合包含Name对象,而不是Ranges 。 棘手的,amirite?

这个任务应该工作,假定命名的范围总是“returnChangeDetectionRange”:

 Set returnDetectionRange = Range("returnChangeDetectionRange") 

如果您想要使用Names集合,可以在包含命名范围的书中使用这个小脚本:

 Option Explicit Sub CoolNamedRangeTest() Dim Nm As Name '<~ we'll use this to iterate through ThisWorkbook.Names Dim returnDetectionRange As Range For Each Nm In ThisWorkbook.Names If Nm.Name = "returnChangeDetectionRange" Then '<~ check the name Set returnDetectionRange = Range(Nm.Name) '<~ assign the range End If Next Nm MsgBox (returnDetectionRange.Address) '<~ validate that it worked here End Sub