在VBA中声明一个数组,异常

时间:2011-12-02 10:55:08

标签: vba

在下面的代码中,VBA告诉我boundary必须是Dim vals(1 To boundary) As Variant行的常量。这是我第一次看到这个。这里发生了什么?

Dim boundary As Integer
boundary = distrib.Count

Dim vals(1 To boundary) As Variant
For i = 1 To boundary
    vals(i) = distrib(i, 3) + distrib(i, 4)
Next i

distrib是一个声明为variant

的数组

3 个答案:

答案 0 :(得分:2)

您不能声明具有非常量值的固定大小数组;相反,您需要将其声明为动态数组(通过省略大小),然后将其重新定位到您想要的边界;

Dim vals() As Variant
ReDim vals(1 To boundary)

答案 1 :(得分:2)

您无法在声明变量的同一操作中分配数据。请尝试使用Redim

Dim boundary As Long
boundary = 10
Dim vals() As Variant
ReDim vals(1 To boundary)

答案 2 :(得分:2)

您最初可以使用变量边界声明一个数组,但是您可以将ReDim更改为变量:

Dim boundary As Integer
boundary = distrib.Count

Dim vals() as Variant
ReDim vals(1 To boundary)
For i = 1 To boundary
    vals(i) = distrib(i, 3) + distrib(i, 4)
Next i