0

Is there anyway that I can put various classes into an array so that instead of hard-coding like:

set var1 = new cls1
set var2 = new cls2

we can do:

varArr = array ( var1, var2...)
clsArr = array (cls1, cls2...)

and now I just loop thru varArr and clsArr to set new class accordingly, like:

sub setNew(x as double)
   set varArr(x) = new clsArr(x)
end sub

I did try but it didn't work, please help me out

Thank you very much !

Triet (mr)

Tim Williams
  • 154,628
  • 8
  • 97
  • 125
  • 1
    You can't do `New clsArr(x)`, `New` is an operator that is used for creating object instances. Storing object references in an array works exactly the same as storing any other `Long` integer in an array, except you need to use the `Set` keyword when assigning to/from an array subscript. You can't do `Array(cls1, cls2)` either, unless the two classes have a predeclared instance. Unclear if you're confusing "class" vs "instance", too. – Mathieu Guindon Jul 29 '20 at 05:22
  • myArray=(New Collection,New Collection, New Collection) works fine so try the same pattern with your classes. But I'd recommend using a Collection or Scripting.Dictionary rather than an array. – freeflow Jul 29 '20 at 07:14

1 Answers1

0

I try, but my knowledge also limited. First of all I do not think you can put class into an array. You can put objects. I also failed to use the array() function. Please see how I proceeded with some demonstration:

This is the class module, containing a value, the property and a primitive print sub:

Private nr As Integer 'Use as identification

Sub cPrint()
    MsgBox "Object ID: " & nr
End Sub

Property Let ID(v As Integer)
    nr = v
End Property

In the module in the first cycle I create the object, put the ID value. In the second one all ID values are printed. I hope you can use it for your purposes.

Sub clsTest()
    Dim varArr(1 To 5) As cls1
    Dim i As Integer
    
    For i = 1 To 5
        Set varArr(i) = New cls1
        varArr(i).ID = i
    Next

    For i = 1 To 5
        varArr(i).cPrint
    Next
End Sub
Viktor West
  • 544
  • 6
  • 9
  • Many tks for your demonstration Viktor, but mine is a little bit different. I have 11 different classes to declare, not just one class with a few instances of that one class like yours. Anyway I will try what Mathieu and Freeflow suggested me. Thanks all ! – user10535974 Jul 29 '20 at 13:52
  • You are right, you have multiply classes. I have found this interesting: https://stackoverflow.com/questions/19373081/how-to-use-the-implements-in-excel-vba – Viktor West Jul 30 '20 at 05:45
  • Many tks Viktor, very interesting. I will dig the link deeper to find the solution for my problem. Thank you again Viktor ! – user10535974 Jul 31 '20 at 06:10