0

Using VB.NET we can store values to array or list in a class which is a public variable and using constructor. Can I do same thing using using vba

Ex:

class Class1
{
    public string  Variable1 { get; set; }
    public string Variable2 { get; set; }

    public List<string> List1 { get; set; }

    public Class1()
    {
        Variable1 = string.Empty;
        Variable2 = string.Empty;
        List1 = new List<string>(0);
    }
}

I want to replicate this in vba.

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
Hulk_1
  • 3
  • 2
  • VBA classes don't have a constructor but they do have a [parameterless] `Class_Initialize` method – Tim Williams Jul 24 '19 at 05:29
  • 1
    It's not possible to exactly replicate constructor parameters in VBA, but a factory method is commonly used. See https://stackoverflow.com/questions/15224113/pass-arguments-to-constructor-in-vba – Ambie Jul 24 '19 at 05:29

1 Answers1

1

Just inserrt to your project Class Module (note that name of this module will be name of your class as well!):

enter image description here

and put this code inside it:

'Class1
Public Var1 As String
Public Var2 As String

Public Collection1 As Collection
' constructor
Public Sub Class_Initialize()
    Var1 = ""
    Var2 = ""
    Set Collection1 = New Collection
    'MsgBox "Instance created!"
End Sub

Then the usage would like this:

Sub test()
    Dim c As Class1
    Set c = New Class1        
End Sub
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69