digitig
digitig

Reputation: 2150

VBA Assign reference to object via constructor

I have the following VBA code in a class module (Access 2010, Option Explicit):

public pObservers as Collection
private Sub Class_Initialize()
    Set pObservers = new Collection
End Sub

When I try to construct a new instance of the class, the constructor fails with a compile error: "Variable not defined".

Yes, I know good practice is that pObservers should be a property - I've simplified it to try to isolate the problem. So how should I initialize an object from a constructor?

(I don't really know VBA at all - you can probably tell.)

Thanks in advance.

Upvotes: 0

Views: 191

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123849

I cannot recreate your issue. In my Access 2010 VBA Class Module named [myClass] I have

Option Compare Database
Option Explicit

Private pObservers As Collection

Private Sub Class_Initialize()
    Set pObservers = New Collection
    pObservers.Add "Collection object initialized."
End Sub

Public Property Get Observers() As Collection
    Set Observers = pObservers
End Property

When I run my test code

Option Compare Database
Option Explicit

Public Sub myClassTest()
    Dim mc As myClass, thing As Variant
    Set mc = New myClass
    For Each thing In mc.Observers
        Debug.Print thing
    Next
End Sub

I see the following in the Immediate Window

Collection object initialized.

Upvotes: 1

Related Questions