0

New to building class modules in VBA and struggling with populating one object which is defined within another object.

For instance, I have two class modules, Class1 and Class2

Class1

Dim mobj As Class2
Public Property Set SetObj(obj As Class2)
     Set mobj = obj
End Property

Class2

Public FirstName As String

These are accessed from a standard module as follows:

Sub test()
Dim X As Class1
Set X = New Class1
Set X.SetObj = New Class2
X.SetObj.FirstName = "Bruce"
End Sub

This however fails in X.SetObj.FirstName = "Bruce" when i get an "Invalid use of property message". Any assistance would be greatly appreciated.

1 Answer 1

3

You are close. Class1:

Private mobj As Class2
Public Property Set Obj(Obj As Class2)
     Set mobj = Obj
End Property

Public Property Get Obj()
     Set Obj = mobj
End Property

Sub (the X.Obj.FirstName line calls the Get property, not the Set property):

Sub test()
  Dim X As Class1
  Set X = New Class1
  Set X.Obj = New Class2
  X.Obj.FirstName = "Bruce"
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the details, but can you explain them a bit better? I THINK I see the changes you made, and why, but can you confirm? I see: (1) Make the other class object Private (2) You pass the object itself in the Set definition of the object (not sure at all how that is possible, seems infinitely recursive, but obviously I'm missing something) (3) The "Get" function just points to the object set as the other class. Am I anywhere close to correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.