查找数组中的平均值(Excel VBA)

时间:2018-02-22 03:42:48

标签: excel excel-vba vba

如何在excel VBA中找到2D数组中保存的值的平均值?我有一个名为"数字"其值为1,2,3,4,6如何将平均值输入名为NumbersAve

的值

1 个答案:

答案 0 :(得分:0)

Application.Average就足够了。

Dim numbers As Variant, NumbersAve As Double

'by rows
Range("A1") = 1
Range("A2") = 2
Range("A3") = 3
Range("A4") = 4
Range("A5") = 6

numbers = Range("A1:A5").Value2
Debug.Print LBound(numbers, 1) & " to " & UBound(numbers, 1) & ", " & _
            LBound(numbers, 2) & " to " & UBound(numbers, 2)  '<~~ 1 to 5, 1 to 1

NumbersAve = Application.Average(numbers)
Debug.Print NumbersAve                   '<~~ 3.2

'by columns
Range("A1") = 1
Range("B1") = 2
Range("C1") = 3
Range("D1") = 4
Range("E1") = 6

numbers = Range("A1:E1").Value2
Debug.Print LBound(numbers, 1) & " to " & UBound(numbers, 1) & ", " & _
            LBound(numbers, 2) & " to " & UBound(numbers, 2)  '<~~ 1 to 1, 1 to 5

NumbersAve = Application.Average(numbers)
Debug.Print NumbersAve                   '<~~ 3.2