我有一个关于 VBA 中的变量和函数的问题。我不会详细说明该项目的内容,希望最初的问题不会变得模糊。如果需要,我可以解释将用于的项目。
是否可以在 VBA 中创建通用变量以便所有函数都可以使用它们?
例如:
Dim testVariable As String
Dim newVariable As String
testVariable = "A"
Function testFunction() As String
....
newVariable = testVariable
End Function
到目前为止,testVariable(当它在函数中时)是“空”
谢谢,
杰西·斯莫瑟蒙
最佳答案
是的,但赋值必须发生在过程内:
Public testVariable As String
Public newVariable As String
Sub SetTestVariable()
testVariable = "A"
End Sub
Function testFunction() As String
....
newVariable = testVariable
End Function
请记住,使用大量全局变量通常是不好的编程习惯。您希望将变量的范围限制在它们将被使用的地方。有关 VBA 中范围的详细信息,请参阅此 Microsoft 知识库文章:Scope of variables in Visual Basic for Applications
关于excel - VBA 函数和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5226001/