在vba中使用类而不是全局变量

时间:2014-05-02 02:03:57

标签: excel vba excel-vba

Excel VBA不允许您使用数组的全局变量,因此我尝试使用类来跟踪我需要的变量。我试图在一个子中创建变量并从另一个子中调用它,但我不知道该怎么做。

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

错误来自Test4(),因为没有启动mc,我尝试启动它但它不是同一个类(我相信)

1 个答案:

答案 0 :(得分:2)

为什么不将Sub Test4()更改为函数而不是调用变量mc:

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

    MsgBox(out(2))
End Function

这可能有用。