是否可以在 Outlook 的 VBA 宏编程中定义静态集合?
Sub mySub()
Static myCollection As VBA.Collection
Set myCollection = New VBA.Collection
myCollection.Add "entry1"
myCollection.Add "entry2"
myCollection.Add "entry3"
End Sub
这样 myCollection 就不必在每次触发宏 mySub() 时重新定义。
最佳答案
VBA 中的静态
变量将在调用之间保留其值。通常,超出范围且未在其他任何地方引用的变量会被销毁; Static
更改变量的声明。
它不会无条件地改变该指令的功能:
Set myCollection = New VBA.Collection
无论上一次运行持有什么引用,我们每次都会覆盖它,从而撤消静态
应该给我们带来的东西。
无论涉及的变量类型如何,您都会遇到相同的问题:问题不在于类型,而在于 Set
指令的无条件性 .
设置条件:
Static myCollection As VBA.Collection
If myCollection Is Nothing Then
Set myCollection = New VBA.Collection
End If
现在 myCollection
在第一次调用时只会是 Nothing
;后续运行将在调用之间保留 myCollection
引用。
与模块级变量差不多:
Option Explicit
Private myCollection As VBA.Collection
Public Sub TestModuleVariable()
If myCollection Is Nothing Then
Set myCollection = New VBA.Collection
End If
With myCollection
.Add "entry" & .Count + 1
Debug.Print .Count
End With
End Sub
Public Sub TestStaticVariable()
Static items As VBA.Collection
If items Is Nothing Then
Set items = New VBA.Collection
End If
With items
.Add "entry" & .Count + 1
Debug.Print .Count
End With
End Sub
使用哪一个取决于模块的其余部分需要如何处理该集合
。如果没有其他人需要知道它,那么当然,将其保留在本地范围内。
请考虑让调用者有责任提供集合作为参数 - 让调用者关心知道它调用了该过程多少次。
Public Sub TestParameter(ByRef items As VBA.Collection)
If items Is Nothing Then
Set items = New VBA.Collection
End If
With items
.Add "entry" & .Count + 1
Debug.Print .Count
End With
End Sub
关于VBA集合可以定义为静态类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53056168/