Search code examples
excelvbafunctionscopeglobal-variables

VBA use Collection for entire workbook


I need to use Collection variable in Global scope. But if i declare collection as public I can use it only in module sheet or worksheet. I need to declare it for entire workbook scope to use it in workbook functions, worksheet functions and module functions.

ThisWorkbook

Public foo As New Collection

Worksheet

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

Module:

Sub col()
MsgBox foo.Count
End Sub

Solution

  • In a Standard Module:

    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
    

    Then you can call it from anywhere in your code.

    ModuleName.TheCollection.Add("whatever")