这是一个关于问题scope。
如果只想变量持续的功能寿命,使用Dim
(简称尺寸)函数或子内声明的变量:
Function AddSomeNumbers() As Integer
Dim intA As Integer
Dim intB As Integer
intA = 2
intB = 3
AddSomeNumbers = intA + intB
End Function
'intA and intB are no longer available since the function ended
一个全球变量(正如SLaks指出的)在使用Public
关键字的函数之外声明。这个变量在运行应用程序的生命周期中可用。就Excel而言,这意味着只要特定的Excel工作簿处于打开状态,这些变量就可以使用。
Public intA As Integer
Private intB As Integer
Function AddSomeNumbers() As Integer
intA = 2
intB = 3
AddSomeNumbers = intA + intB
End Function
'intA and intB are still both available. However, because intA is public, '
'it can also be referenced from code in other modules. Because intB is private,'
'it will be hidden from other modules.
您也可以是通过与Private
关键字声明它们的特定模块(或类)内只访问的变量。
如果您正在构建一个大型应用程序,并且觉得需要使用全局变量,那么我会建议为您的全局变量创建一个单独的模块。这应该有助于您在一个地方跟踪它们。
+1 7年后仍然有用。但是,在对象变量和数据变量方面还有一些额外的细微差别吗?我遇到了一个与引发新问题的对象变量范围相关的问题。非常感谢,如果你有时间看看。 https://stackoverflow.com/q/46058096/5457466 – Egalth 2017-09-05 19:22:55