Excel VBA全局变量

Rya*_*oza 2 excel vba excel-vba

可以通过另一个模块中的另一个方法访问ThisWorkbook Excel对象的Private Sub Workbook_Open中声明的变量吗?我想在代码的开头声明并分配一个变量,任何使用它的模块都可以更改该变量。当下一个方法调用该更改时,应将其反映在变量中。

我在模块中有一个子代,它为公共变量赋值。我要求由module1设置的该值可被module2的值访问

Mat*_*don 6

一个全局变量需要有Public可访问性,并且在声明模块范围的一个在标准模块(.BAS)。

Option Explicit
Public Foo As Long ' global variable
Run Code Online (Sandbox Code Playgroud)

全局变量的问题在于,代码中任何地方都可以读取写入它们:全局状态很容易导致无法维护的意大利面条式代码,应尽可能避免使用。

有多种选择,特别是使用参数

Option Explicit

Public Sub SomeEntryPoint()
    Dim foo As Long ' local variable
    DoSomething foo
    MsgBox foo 'prints 42
End Sub

'this procedure could be in any module, public.
Private Sub DoSomething(ByRef foo As Long)
    foo = 42 'byref assignment; caller will receive the updated value
End Sub
Run Code Online (Sandbox Code Playgroud)

如果需要由声明该变量的模块编写该变量,但又需要从其他地方读取该变量,则可以使用properties

Option Explicit
Private foo As Long ' private field

Public Sub DoSomething()
    'do stuff...
    foo = 42
    '...
End Sub

Public Property Get SomeFoo() As Long
    SomeFoo = foo
End Property
Run Code Online (Sandbox Code Playgroud)

现在,在代码模块可以写入foo根据需要,和其它模块只能 foo通过SomeFoo属性-假设字段和属性定义在Module1

Debug.Print Module1.SomeFoo 'gets the value of the encapsulated private field
Run Code Online (Sandbox Code Playgroud)


Vit*_*ata 5

以@David 的回答为基础,这是如何使用 Dim 和 Public 及其差异(在模块中,命名为Modul1write 以下并运行TestMe):

Dim a           As String
Public b        As String
Private c       As String
Global d        As String

Private Sub TestA()
'Whatever is not declared in TestMe, would take its value from here for the print.
'^-If it is declared, the value would be attached to the public/private/dim/glb above.    
    a = 11
    b = 22
    c = 33
    d = 44        
End Sub

Private Sub TestMe()

    Dim a       As String
    'Dim b       As String
    'Dim c       As String
    Dim d       As String

    a = 1
    b = 2
    c = 3
    d = 4

    TestA

    Debug.Print a; vbTab; Modul1.a
    Debug.Print "----------------"
    Debug.Print b; vbTab; Modul1.b
    Debug.Print "----------------"
    Debug.Print c; vbTab; Modul1.c
    Debug.Print "----------------"
    Debug.Print d; vbTab; Modul1.d

End Sub
Run Code Online (Sandbox Code Playgroud)

这是你得到的:

1    11
----------------
22    22
----------------
33    33
----------------
4    44
Run Code Online (Sandbox Code Playgroud)