Skip to main content
Post Reopened by janos
Post Closed as "Not suitable for this site" by Marc-Andre, Malachi, Edward, Quill, SuperBiasedMan
Source Link
SRS
  • 41
  • 1
  • 4

Using Array to store calculations in VBA

I have the following VBA code, which works perfectly well to calculate "q"

However, the code is very slow and that is due to the large number of q's being calculated (roughly 7.2m q's are being calculated).

So I thought the best way to proceed is to try store the calculated q values in an array and then dump them into the spreadsheet once all of them are calculated.

The q's will vary for each i and j combination. I have tried to add the following to try and store results in an array to the to the main code given below:

Dim results() as variant
Redim results(I,j)
Results (I,j)= q
Range("G5").value=results

This did not work and I know it does not even look half right, but if you could help me spot where I am going wrong it would be really appreciated.

Sub mort()
Dim age As Integer
Dim month As Integer



For i = 0 To ActiveSheet.Range("F5", Range("F5").End(xlDown)).Count

For j = 0 To ActiveSheet.Range("G3", Range("G3").End(xlToRight)).Count

    gender = Range("C5").Offset(i, 0)

    If gender = "F" Then
    mortable = Worksheets("Female Tabs").Range("A3:C122")
    Else
    mortable = Worksheets("Male Tabs").Range("A3:C122")
    End If

month = Range("G3").Offset(0, j)
age = WorksheetFunction.RoundDown(Range("F5").Offset(i, 0) + (month - 3) / 12, 0)

If age < 119 Then

    a = (12 - ((month - 3) Mod 12)) / 12
    a1 = Application.VLookup(age, mortable, 3, False)


    b = ((month - 3) Mod 12) / 12
    b1 = Application.VLookup(age + 1, mortable, 3, False)

Else

a1 = 0
b1 = 0

End If

q = (1 / 12) * (a * a1 + b * b1)

Worksheets("Policy Mortality Qx").Range("G5").Offset(i, j).Value = q

Next j   
Next i

End Sub