atomant
atomant

Reputation: 339

Using classes instead of global variables in vba

Excel VBA won't let you use global variables of arrays so I am trying to use a class to keep track of the variables I need. I am trying to create the variable in one sub and call it from another, but I don't know how to do it.

Sub Test3()
 Dim mc As cVars
 Set mc = New cVars

 Dim ex() As Double
 ReDim ex(1 To 5)

 For i = 1 To 5
  ex(i) = i
 Next i

 mc.Arr = ex

 Call Test4
End Sub

Sub Test4()
 Dim out() As Double
 ReDim out(1 To 5)
 out = mc.Arr

 MsgBox (out(2))
End Sub

...

Option Explicit
Private pArr() As Double
Public Property Get Arr() As Double()
    Arr = pArr()
End Property
Public Property Let Arr(p() As Double)
    pArr = p()
End Property

The error comes in Test4() because there is no mc initiated, I tried initiating it but it then is not the same class (I believe)

Upvotes: 0

Views: 526

Answers (1)

Moiety Design
Moiety Design

Reputation: 473

Why not change Sub Test4() to a function instead calling a variable mc:

Function Test4(mc As cVars)
    Dim out() As Double
    ReDim out(1 To 5)
    out. mc.Arr

    MsgBox(out(2))
End Function

That may work.

Upvotes: 2

Related Questions