## Calculate Average with Do While Loop

How to calculate average with a ‘do while’ loop. Calculating average using the worksheet function ‘AVERAGE’ is straight-forward. We can use the same worksheet function average in VBA code as shown below:
Sub calAvg()
dim avg as Long
Set myRange = Range(“B2:B6”)
avg = Application.WorksheetFunction.Average(myRange)
MsgBox (“The average is “) & avg
End Sub

However, the above code has its limitations especially with respect to data that expands automatically or dynamically. Now the looping process using a ‘do while’ loop can easily provide a solution to calculation of the average of dynamically expanding data. In the process we also learn a few interesting things about programming in general and VBA in particular. Watch the video below:

Watch this video on YouTube.

Here’s the complete VBA code to find the average of a set of changing data:

Sub avgUsingDoWhile()
Dim r As Long, totsal As Long, salcount As Long, avgsal As Long
r = 2
totsal = 0
salcount = 0

Do While Cells(r, 1) <> “”
totsal = totsal + Cells(r, 2).Value
salcount = salcount + 1
r = r + 1
Loop

avgsal = totsal / salcount
MsgBox “The average salary is ” & avgsal

End Sub