Calculating an average in VBA and ignore blank cells in range

totalnatal

New Member
Joined
Jun 9, 2010
Messages
33
Hello,

I have 10 cells in row A containing weights
I have 10 cells in row B containing values

I'm trying to do a weighted average. however', sometimes i may not have 10 values but maybe 8 or 2.

What code would i need to so that the average ignores the blank cells.

Thank you
 

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney
Try
Code:
Sub WeightedAvg()
'kpark
    Dim i As Integer, weight As Long, val As Long, count As Integer, sum As Long
    For i = 1 to 10 'Assuming your values/weights are side by side and are in col A and col B 1:10
        weight = Range("A" & i).Value
        val = Range("B" & i).Value
        If weight <> 0 And val <> 0 Then
             count = count + 1
             sum = weight * val + sum
        End If
    Next i
 
    MsgBox "Your average is " & sum / count
End Sub
 
Upvote 0
I'm assuming that equvalient rows are blank, i.e. if A4 is blank, so is B4

On that basis, try:
Code:
Sub Lege()
 
Dim i As Long, j As Long, myAve As Long
 
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With
 
j = 0

For i = 1 To 10
    If Len(Range("A" & i)) > 0 Then
        myAve = myAve + (Range("A" & i) * Range("B" & i))
        j = j + 1
    End If
Next i
 
If j > 0 Then
    myAve = myAve / j
    MsgBox "Average of the values is: " & myAve
Else
    MsgBox "No values to Average"
End If
 
With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
End With
 
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,605
Messages
6,179,860
Members
452,948
Latest member
UsmanAli786

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top