Reputation: 216
I want to find the average of some set of values.
I am doing this:
Dim avg(1 To 14)
For i = 1 To 14
Dim helparray(1 To 3)
For j = 1 To 3
helparray(j) = Sheets("mysheet").Cells(i, j)
Next j
Avg(i) = Application.Average(helparray)
Erase helparray
Next i
What happens with the declaration of helparray
? Is it be redeclared on every iteration? Or is it only cleaned?
How do I create a NEW array on every iteration (and then delete it)?
Upvotes: 0
Views: 101
Reputation: 54923
avg
, as you put it, it only gets cleaned.helparray
and later redim
it to the size you need. And when you erase it, it will be deleted (will not occupy 'space' in memory).The Code
Option Explicit
Sub testArrays()
Dim i As Long
Dim j As Long
Dim avg(1 To 14)
Dim helparray() As Variant
For i = 1 To 14
ReDim helparray(1 To 3)
For j = 1 To 3
helparray(j) = Sheets("mysheet").Cells(i, j)
Next j
avg(i) = Application.Average(helparray)
Erase helparray
Next i
Debug.Print Join(avg, vbLf)
End Sub
Sub testArrays2()
Dim i As Long
Dim j As Long
Dim avg(1 To 14)
For i = 1 To 14
avg(i) = Application.Average(Sheets("mysheet").Cells(i, 1).Resize(, 3))
Next i
Debug.Print Join(avg, vbLf)
End Sub
Upvotes: 1
Reputation: 1944
I haven't tested this but try the below:
Dim avg(1 To 14)
Dim helparray As Variant
For i = 1 To 14
With ThisWorkbook.Worksheets("<name of your sheet here>")
helparray = .Range(.Cells(i, 1), .Cells(i, 3))
End With
avg(i) = Application.Average(helparray)
Next i
Upvotes: 0