0

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)

5
  • 3
    I can set a Public variable that's an array of Doubles in one module and refer to it in another module. Commented May 2, 2014 at 3:08
  • 1
    I think @DougGlancy is right here, I actually constructed a global string array in my answer not five minutes ago... stackoverflow.com/questions/23419422/…
    – Dan Wagner
    Commented May 2, 2014 at 4:20
  • I try to add "Public Inputs() as Double" to the beginning and I get an error that says "Compile error: Constants, fixed-length strings, arrays, user-defined types and Declare statements not allowed as Public members of object modules." I've tried using "Global" instead of Public as well
    – atomant
    Commented May 2, 2014 at 5:44
  • 1
    Got it, I was in Excel Objects but I guess I should be putting my code in Modules? It seems to be working now, thanks
    – atomant
    Commented May 2, 2014 at 5:55
  • Sorry, I should have specified that it needs to be a regular module. Glad you figured it out. Commented May 2, 2014 at 13:54

1 Answer 1

2

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.