Hi Karen,
Paste the following code into a module.
===================================================
Public Const strError As String = "Error"
Public Function AverageAny(ParamArray var() As Variant) As Variant
' Average function that accepts any number of parameters.
' Author: Clifford Bass
' Parameters: Any number accepted, but only numeric values will be used
' Returns: The average of all the numerical values, if there are any,
otherwise Null
Dim i As Integer
Dim intCount As Integer
Dim dblSumValues As Double
On Error GoTo AverageAny_Error
intCount = 0
dblSumValues = 0
For i = LBound(var()) To UBound(var()) Step 1
SumAndCount var(i), dblSumValues, intCount
Next i
If intCount > 0 Then
AverageAny = dblSumValues / intCount
Else
AverageAny = Null
End If
AverageAny_Exit:
Exit Function
AverageAny_Error:
AverageAny = strError
Resume AverageAny_Exit
End Function
Private Sub SumAndCount(ByVal varItem As Variant, ByRef dblSumValues As
Double, _
ByRef intCount As Integer)
' Helper routine for AverageAny
Dim i As Integer
If Not IsNull(varItem) Then
If IsArray(varItem) Then
For i = LBound(varItem) To UBound(varItem) Step 1
SumAndCount varItem(i), dblSumValues, intCount
Next i
Else
If IsNumeric(varItem) Then
dblSumValues = dblSumValues + varItem
intCount = intCount + 1
End If
End If
End If
End Sub
===================================================
Use it as follows:
Private Sub SomeSub()
Dim varResult As Variant
varResult = AverageAny(Field1, Field2, Field3, Field4, Field5)
If IsNull(varResult) Then
' No values found
.....
Else
If varResult = "Error" Then
' An error occurred
....
Else
' An average has been calculated successfully
........
End If
End If
End Sub
In theory you can specify an unlimited number of fields. The only
exception is if you are using it directly in a query, in which case, if I
recall corrrectly, you are limited to 29. When you are calling it from code
you can actually pass multiple arrays of values in as the parameters.
Hope this helps,
Clifford Bass