首页 > 解决方案 > VBA 对整个工作簿使用集合

问题描述

我需要在全局范围内使用 Collection 变量。但是,如果我将集合声明为公共,我只能在模块表或工作表中使用它。我需要为整个工作簿范围声明它以在工作簿函数、工作表函数和模块函数中使用它。

本工作簿

Public foo As New Collection

工作表

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = False
row= Target.Row
column= Target.Column
        If Cells(row, 2).Value = "" Then
        Exit Sub
        Else
                If Cells(row, 1).Value = "" Then

                    foo.Add row- 5

                    Cells(row, 1).Value = "X"
                    Cells(row, 2).Select
                    Cells(row, 14).Value = True
                Else

                    foo.Remove row- 5

                    Cells(row, 1).Value = ""
                    Cells(row, 2).Select
                    Cells(row, 14) = False
                End If
        End If
Application.ScreenUpdating = True
End Sub

模块:

Sub col()
MsgBox foo.Count
End Sub

标签: excelvbafunctionscopeglobal-variables

解决方案


在标准模块中:

Private m_collection As Collection

Public Property Get TheCollection() As Collection
    If m_collection Is Nothing Then Set m_collection = New Collection
    Set TheCollection = m_collection 
End Property

然后,您可以从代码中的任何位置调用它。

ModuleName.TheCollection.Add("whatever")

推荐阅读