VBA函数和variables
我有一个关于VBA中的variables和函数的问题。 我不打算包括项目到底是什么,希望最初的问题不会变得模糊。 如果需要的话,我可以解释这个项目将被使用。
是否有可能在VBA中创build通用variables,以便所有function都可以使用它们?
例如:
Dim testVariable As String Dim newVariable As String testVariable = "A" Function testFunction() As String .... newVariable = testVariable End Function
截至目前,testVariable(在函数中)是“Empty”
谢谢,
Jesse Smothermon
是的,但是价值分配必须发生在程序中:
Public testVariable As String Public newVariable As String Sub SetTestVariable() testVariable = "A" End Sub Function testFunction() As String .... newVariable = testVariable End Function
请记住,使用大量全局variables通常是不好的编程习惯。 您想要将variables的范围限制在将要使用的位置。 有关VBA中的作用域的更多信息,请参阅此Microsoft知识库文章: Visual Basic for Applications中variables的作用域
是否有可能在VBA中创build通用variables,以便所有function都可以使用它们?
是的,虽然你需要声明范围如mwolf02所述。 然而 ,你不能在VBA中做的事情是在VBScript之外的函数或过程调用之外。
另外,如果你真的需要全局variables,你应该得到一个命名scheme,区分全局variables和本地声明variables(例如用g_
前缀)。 你可以得到这个令人困惑的情况:
Public testVariable as String Public Sub Main() Call Foo() Call Bar() End Sub Public Sub Foo() testVariable = "Foo" End Sub Public Sub Bar() Dim testVariable As String testVariable = "Bar" End Sub
即使Bar
被稍后调用, testVariable
的值testVariable
将是“Foo”。 事实上,从Bar内部引用全局variablestestVariable
是没有办法的,因为它声明了一个名字相同的局部variables。
保留variables的任何子/function,所以他们成为全局
然后,在运行任何包含默认设置的代码(如代码)之前调用init函数
Sub InitGlobalVars testVariable = "A" End Sub Sub MyProjectMain InitGlobalVars .... ... rest of code End Sub
很简单的例子:
Dim testVariable As String Dim newVariable As String Sub setVariable(ByVal x as string) testVariable = x End Sub Function testFunction() As String testFunction = testVariable End Function Sub test() Call setVariable("A") MsgBox testFunction() Call setVariable("B") MsgBox testFunction() End Sub
正如其他文章中提到的那样:全局variables是一个不好的习惯,必须在子/函数内部赋值。 它们也应该在模块的开头定义。
或者,您可以使用全局常量而不是variables 。
Public Const TESTVARIABLE = "A"
我相信这更适合你的问题,而不是在一个特定的function内设定值。
Obs1 .:全局常量(通常)以大写字母存储。
Obs2 .:您不能在工作表代码中设置全局常量。 使用一个特定的模块(例如global.bas)来做到这一点。
RGDS