在 VBA 中初始化全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4987713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:09:13  来源:igfitidea点击:

Initialising global variables in VBA

vbaexcel-vbaexcel

提问by Hong Ooi

In Excel 2003, how can I declare global variables and initialise them only once, ie when the workbook is opened?

在 Excel 2003 中,如何声明全局变量并仅将它们初始化一次,即在打开工作簿时?

I have some parameters that are used by a few macros: paths to input files, basically. At the moment, my code looks like this:

我有一些宏使用的一些参数:基本上是输入文件的路径。目前,我的代码如下所示:

global path1, path2 as string

sub initPaths
    path1 = 'path\to\file1'
    path2 = 'path\to\file2'
end sub

Then, whenever I need to use file1 or file2 in a subroutine or function, I insert a call to initPaths. But this seems rather inelegant; I'd like to be able to set the paths only once rather than repeatedly.

然后,每当我需要在子例程或函数中使用 file1 或 file2 时,我都会插入对initPaths. 但这似乎很不雅观;我希望能够只设置一次而不是重复设置路径。

回答by Steve Jorgensen

From your example, it looks like what you want are constants, not global variables.

从您的示例中,看起来您想要的是常量,而不是全局变量。

Public Const PATH1 = "path\to\file1"
Public Const PATH2 = "path\to\file2"

If you really do need to use code to determine the values, but only want to initialize them once, you can use lazy-initialization...

如果确实需要使用代码来确定值,但只想初始化一次,则可以使用延迟初始化...

Private mstrPath1 As String
Private mstrPath2 As String

Public Function Path1() As String
    if mstrPath1 = vbNullString Then
        ' Initialize mstrPath1 value here.
    End If
    Path1 = mstrPath1
End Function

Public Function Path2() As String
    if mstrPath2 = vbNullString Then
        ' Initialize mstrPath2 value here.
    End If
    Path2 = mstrPath2
End Function

The nice thing here is that if your code ever gets reset, the values simply get re-initialized again next time you access them via their respective functions.

这里的好处是,如果您的代码被重置,下次您通过各自的函数访问它们时,这些值只会再次重新初始化。

Note that global variables are to be avoided as much as possible, and you should always prefer private global variables over public ones where possible. Use globals and public globals where necessary, but only where necessary.

请注意,应尽可能避免使用全局变量,并且在可能的情况下,您应该始终选择私有全局变量而不是公共全局变量。在必要时使用全局变量和公共全局变量,但仅在必要时使用。