VBA中的静态变量非常简单:
Public Sub foo()
Static i As Integer
i = i + 1
Debug.Print i
End Sub
输出(多次调用时):
1
2
3
...
问题是,VBA不支持在与声明相同的行上初始化变量(不包括:
用于在一行上放置两行):
Public Sub foo()
Dim i As Integer = 5 'won't compile!
Dim j As Integer
j = 5 'we have to do this instead
End Sub
这与静态变量冲突:
Public Sub foo()
Static i As Integer 'we can't put an initial value here...
i = 5 'so this is how we'd usually initialize it, but...
i = i + 1
Debug.Print i
End Sub
您可能会看到发生了什么-每次foo
调用变量时所做的第一件事就是将其自身设置回5。输出:
6
6
6
...
如何在VBA中将静态变量初始化为默认值以外的值?还是只是VBA丢球?
如果要保留静态语义而不切换到全局变量,执行此操作的一种方法是嗅探默认值,然后设置初始条件:
Static i As Integer
if (i = 0) then i = 5
更安全的选择也许是
Static i As Variant
if isempty(i) then i = 5
或者
Public Sub foo(optional init as boolean = false)
Static i As Integer
if init then
i = 5
exit sub
endif
您可能还可以使用默认属性创建一个类并使用class_initialize
它,但这可能有点麻烦。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句