VBA集合可以定义为静态类型吗?

标签 vba collections outlook static

是否可以在 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/

相关文章:

vba - 使用变量作为工作表名称

excel - 如何提取文本字符串中的文本

scala - Scala排序是否稳定?

excel - 将数据从 Excel 导出到 Outlook

java - "text/plain; charset=ISO-8859-2"电子邮件正文类型中的新行

Excel - 如何强制日期为 dd/mm/yyyy 以进行数据验证

vba - HTA 如何获取当前用户的用户名?

java - 计算元素数组的 MIN、MAX 的程序,其中每个元素都是 Map<String,Float>

java - 使用 Java lambda 或流将 POJO 列表转换为其 ID 列表

excel - 使用 VBA 从 Outlook 2010 保存 .XLSX 附件