Excel VBA全局变量 [英] Excel VBA Global variable

查看:534
本文介绍了Excel VBA全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can variable declared in the Private Sub Workbook_Open of the ThisWorkbook Excel Object be accessed by another method in another module? I want to declare and assign a variable at the start of my code that can be changed by any module using it. This change should be reflected in the variable when the next method calls it.

我在模块中有一个子程序,该子程序将值分配给公共变量. 我要求module1设置的该值才能被module2的访问

I have a sub in a module that assigns value to the public variable. I require this value set by module1 to be accessible to that of module2

推荐答案

在@David的答案的基础上,这是如何使用Dim和Public及其区别的方法(在名为Modul1的Modul中,编写以下内容并运行TestMe):

Building on the answer of @David, this is how to use Dim and Public and their differences (in a Modul, named Modul1 write the following and run 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

这就是你得到的:

1    11
----------------
22    22
----------------
33    33
----------------
4    44

这篇关于Excel VBA全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆