填充一维动态数组

时间:2017-09-18 08:51:50

标签: excel vba

我有这样的代码。

Dim sums() As Single
dim n as integer
For n = 0 To ActiveCell.Value - 2
    sums(n) = Abs(Application.WorksheetFunction.SumIf(Range(Cells(i + m, 6), Cells(j - 1, 6)), Range("F" & i + m).Value, Range(Cells(i + m, 17), Cells(j - 1, 17))))
Next n

我收到sums(n)= ....的错误消息我想根据公式用数组填充数组。 E.G我有activecell值3,然后我希望有两个值的数组,如sums(0) = abs(sumif..) and sums(1)= abs(sumif..)

我尝试计算没有数组的公式,因为sum1 =公式并且它有效,但是一旦我将其更改为数组,因为有时我会在那里有2,3个更多的值,它不起作用

2 个答案:

答案 0 :(得分:0)

您需要先调整数组大小。在循环之前使用Redim来执行此操作:

Redim sums(0 to ActiveCell.Value - 2)
For n = 0 To ActiveCell.Value - 2
...

您可以在代码中多次使用Redim,但请注意,如果要保留数组的内容,则必须使用Redim preserve并且这很慢,因为完整的数组是重建。因此,您应该避免在循环中使用Redim preserve

答案 1 :(得分:0)

尝试以下更改:

Option Explicit

Sub sums_()

Dim sums() As Single
Dim n As Integer
Dim i As Integer
Dim m As Integer
Dim j As Integer

'assign the values or range of values for i,m,j


ReDim sums((ActiveCell.Value - 2) + 1)

For n = 0 To ActiveCell.Value - 2
sums(n) = Abs(Application.WorksheetFunction.SumIf(Range(Cells(i + m, 6), Cells(j - 1, 6)), Range("F" & i + m).Value, Range(Cells(i + m, 17), Cells(j - 1, 17))))
Next n


End Sub