VBA Creating a Custom Class Class module scope, instancing and re-use


Example

By default, a new class module is a Private class, so it is only available for instantiation and use within the VBProject in which it is defined. You can declare, instantiate and use the class anywhere in the same project:

'Class List has Instancing set to Private
'In any other module in the SAME project, you can use:

Dim items As List
Set items = New List

But often you'll write classes that you'd like to use in other projects without copying the module between projects. If you define a class called List in ProjectA, and want to use that class in ProjectB, then you'll need to perform 4 actions:

  1. Change the instancing property of the List class in ProjectA in the Properties window, from Private to PublicNotCreatable

  2. Create a public "factory" function in ProjectA that creates and returns an instance of a List class. Typically the factory function would include arguments for the initialization of the class instance. The factory function is required because the class can be used by ProjectB but ProjectB cannot directly create an instance of ProjectA's class.

     Public Function CreateList(ParamArray values() As Variant) As List
         Dim tempList As List
         Dim itemCounter As Long
         Set tempList = New List
         For itemCounter = LBound(values) to UBound(values) 
             tempList.Add values(itemCounter)
         Next itemCounter
         Set CreateList = tempList
     End Function
    
  3. In ProjectB add a reference to ProjectA using the Tools..References... menu.

  4. In ProjectB, declare a variable and assign it an instance of List using the factory function from ProjectA

     Dim items As ProjectA.List
     Set items = ProjectA.CreateList("foo","bar")
    
     'Use the items list methods and properties
     items.Add "fizz"
     Debug.Print items.ToString()
     'Destroy the items object
     Set items = Nothing