VBA 对整个工作簿使用集合

VBA use Collection for entire workbook

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

本工作簿

Public foo As New Collection

工作sheet

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

在标准模块中:

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")