Sometimes we need to do calculations based on the data in our excel sheets and put the results back to the sheets. We can do these calculations for each cell one by one using a for next loop. But it can be inefficient in the running stage of the program. It won't be an issue if we only deal with sheets only have data in few rows. But in real world, we have to deal with sheets which have thousands of rows of data.
So in this post I will explain you how to calculate efficiently using arrays.
Here is the example we have.
It is a sample data set of employees of a company. Column D has their monthly income and column E has the tax rate. According to the above data, tax rate equals to 10%. Normally tax rate increases with the salary level. But to make this example simple, I have set it to 10% for any salary level. So now what we need to do is calculate Annual income, Tax and Remaining.
So let's start the coding.
First we need to declare variables.
Dim WS As Worksheet
Dim MonthlyIncome() As Variant Dim Answers() As Variant Dim D1 As Long Dim i As Long |
We are going use two variant type arrays for this example. Next we need to set the worksheet to declared variable.
Set WS = Worksheets("Sheet1") |
Below line will add existing data to MonthlyIncome array.
MonthlyIncome = WS.Range("D2:D19") |
We are going to store calculated results in a different array call Answers. For that, we need to determine it's dimensions. Following line will assign it's first dimension to the variable D1.
D1 = UBound(MonthlyIncome, 1) |
As we need to store three different result for each employee, second dimension should equal to 3. So we can Redim the Answers array as follows.
ReDim Answers(1 To D1, 1 To 3) |
Then below, for next loop will calculate the results for each employee and store the results in Answers array.
For i = 1 To D1 Answers(i, 1) = MonthlyIncome(i, 1) * 12 Answers(i, 2) = (MonthlyIncome(i, 1) * 12 * 10) / 100 Answers(i, 3) = Answers(i, 1) - Answers(i, 2) Next i |
Then we can write Answers array to worksheet.
WS.Range(Range("F2"), Range("F2").Offset(D1 - 1, 2)).Value = Answers |
Finally it is good practice to erase the arrays
Erase MonthlyIncome Erase Answers |
So that is the step by step explanation about how to use arrays for calculations. Below is the full code for above example.
Dim WS As Worksheet
Dim MonthlyIncome() As Variant Dim Answers() As Variant Dim D1 As Long Dim i As Long Set WS = Worksheets("Sheet1") MonthlyIncome = WS.Range("D2:D19") D1 = UBound(MonthlyIncome, 1) ReDim Answers(1 To D1, 1 To 3) For i = 1 To D1 Answers(i, 1) = MonthlyIncome(i, 1) * 12 Answers(i, 2) = (MonthlyIncome(i, 1) * 12 * 10) / 100 Answers(i, 3) = Answers(i, 1) - Answers(i, 2) Next i WS.Range(Range("F2"), Range("F2").Offset(D1 - 1, 2)).Value = Answers Erase MonthlyIncome Erase Answers |
Following is the result you will get after running the code.