简体   繁体   English

VBA参考命名范围

[英]VBA Referring to named range

I'm just starting to used named references within my VBA, but have hit a minor problem. 我刚开始在我的VBA中使用命名引用,但遇到了一个小问题。

I have a named reference called "SiteCount" that counts the number of sites in a column 我有一个名为“SiteCount”的命名引用,它计算列中的站点数

=COUNTA(Data!$B:$B)

It is saved as Workbook in scope and works when I use it in a cell as 它在范围内保存为工作簿,当我在单元格中使用它时可以工作

=SiteCount

I thought I could use this in my code rather than replicate the calculation, however I can not save the value even just as 我以为我可以在我的代码中使用它而不是复制计算,但是我甚至无法保存该值

Sitecount = Range("SiteCount") 

I have tried using the worksheet name as well, but I get the same 1004 "Method range of object global failed" 我也试过使用工作表名称,但我得到相同的1004“方法范围的对象全局失败”

I'm guessing it's something very simple. 我猜这是非常简单的事情。 but I can't figure it out. 但我无法弄清楚。 Advice is gratefully received :) 建议很感激:)

Evaluate() should do since it's a formula name not a named range Evaluate()应该这样做,因为它是一个公式名称而不是命名范围

Dim siteCount as Long
siteCount = Evaluate("SiteCount")

It's not a named range, it's a named formula, so you have to refer to it differently. 它不是命名范围,它是一个命名公式,所以你必须以不同的方式引用它。 You can use: 您可以使用:

lSiteCount = [SiteCount]

note that the variable name must not be the same as the formula name! 请注意,变量名称不能与公式名称相同!

or 要么

SiteCount = Sheets("Data").Evaluate("SiteCount")

or 要么

SiteCount = Application.Evaluate("SiteCount")

If you want to get the values of specific named formulas then: 如果要获取特定命名公式的值,则:

Sub WhatsInAName()
    For Each n In ActiveWorkbook.Names
        If n.Name = "SiteCount" Then
            MsgBox n.Value & vbCrLf & Evaluate(n.Value)
        End If
    Next n
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM