1

Try to create an object with a constructor in vba, I found that answer: pass argument to constructor in vba

But I can not make it works. I missed something.

I use the excel 2010 vba editor. I get a "compile error, syntax error" on InitiateProperties line when I launch MacroTest(), the code here:

in TestClass (created with modul class):

Option Explicit

Private pInfo1 As String
Private pInfo2 As String

Public Sub InitiateProperties(info1 As String, info2 As String)
   pInfo1 = info1
   pInfo2 = info2
End Sub

in factory (created as modul)

   Set CreateTestClass = New TestClass
   CreateTestClass.InitiateProperties(info1, info2)
End Function

in Module1*

Sub MacroTest()
   Dim myObject As TestClass
   myObject = CreateTestClass("hello", "bye")
End Sub    

the line :

CreateTestClass.InitiateProperties(info1, info2)

appear to be red

I do not see where I m wrong, it's probably obvious.

Thanks in advance.

Community
  • 1
  • 1
yoh
  • 154
  • 1
  • 10

3 Answers3

2

As discussed in other comments, you need to replace:

CreateTestClass.InitiateProperties(info1, info2)

with

Call CreateTestClass.InitiateProperties(info1, info2)

You'll also find an error in Module1 where:

myObject = CreateTestClass("hello", "bye")

should read:

Set myObject = CreateTestClass("hello", "bye")

since you are assigning a reference to the object returned by the CreateTestClass factory function to myObject.

stucharo
  • 865
  • 5
  • 19
1

Replace:

Set CreateTestClass = New TestClass
   CreateTestClass.InitiateProperties(info1, info2)
End Function

With EITHER:

Set CreateTestClass = New TestClass
   CreateTestClass.InitiateProperties info1, info2 
End Function

OR this:

 Set CreateTestClass = New TestClass
  Call CreateTestClass.InitiateProperties(info1, info2)
End Function
AnalystCave.com
  • 4,884
  • 2
  • 22
  • 30
0

Try removing the ( ) I assume that info1 and info2 are passed as parameters to the function in factory and are sting values.

Tom
  • 747
  • 5
  • 16