一个 VBA 函数,它接受数组(任何等级)和具有多个区域的范围(不连续的范围,如 A4:B6、C11:D15),甚至是公式中的范围的联合。它会跳过非数字数据类型(包括日期、布尔值、空格等)。
您可以在 VBA 代码中使用它,也可以在工作表公式中将其用作 UDF,例如:
“=RMS(A1:A10)”(基本用法)
"=RMS(A1:A10,C1:C10)" (多个范围(或数组))
"{=RMS({1,2,3,4})}"(使用 Ctrl+shift+enter 输入的数组公式)
Function RMS(ParamArray args()) As Double
Dim arg, arr, area As Range, ss As Double, n As Long
For Each arg In args
If TypeOf arg Is Range Then
For Each area In arg.Areas
arr = area.value
If VarType(arr) < vbArray Then
queryRmsElements Array(arr), ss, n
Else
queryRmsElements arr, ss, n
End If
Next area
ElseIf VarType(arg) > vbArray Then
queryRmsElements arg, ss, n
Else
Err.Raise 1, "RMS", "Invalid Argument"
End If
Next arg
RMS = (ss / n) ^ 0.5
End Function
Private Sub queryRmsElements(ByRef elements, ByRef ss As Double, ByRef n As Long)
Static element As Variant
'Enumerate to cover rank > 1 (vs. Iterate)
For Each element In elements
Select Case VarType(element)
Case VbVarType.vbByte, _
VbVarType.vbCurrency, _
VbVarType.vbDecimal, _
VbVarType.vbDouble, _
VbVarType.vbInteger, _
VbVarType.vbLong, _
VbVarType.vbSingle
ss = element ^ 2 + ss
n = n + 1
Case Else
End Select
Next element
End Sub