计算列中所选单元格的平均值

时间:2018-03-09 00:41:27

标签: vba excel-vba excel

我正在尝试从列中标记单元格,然后将范围存储到变量中。我想将该变量用于另一个宏来计算给定范围内的平均值。

Sub UserRang()

Dim SelRange As Range

Set SelRange = Selection
Rng1 = SelRange.Address
MsgBox "You selected: " & Rng1

End Sub


Sub GradeAve()

GradeAverage = Application.WorksheetFunction.Average(Rng1)
MsgBox "The grade average is: " & GradeAverage

End Sub

2 个答案:

答案 0 :(得分:0)

为什么你不能只使用AVERAGE工作表功能并跳过中间的'变量'?

离。 “= AVERAGE(A1:A5,A9,A12)”

如果要保存和维护静态变量(或类似静态变量的东西),VBA并不是很好。

答案 1 :(得分:0)

Rng1需要在模块顶部声明,并且应该是一个范围而不是地址字符串,因为Average需要一个范围作为参数。

Public Rng1 as Excel.Range  

Sub UserRang()
Dim SelRange As Range

Set SelRange = Selection
Set Rng1 = SelRange
MsgBox "You selected: " & Rng1.Address

End Sub

更好的是,使用返回范围的函数而不是sub。

Public Function GetUserSelection() as Excel.Range
  Set GetUserSelection = Selection
End Function

Sub GradeAve()

  GradeAverage = Application.WorksheetFunction.Average(GetUserSelection)
  MsgBox "The grade average of " & GetUserSelection.Address & " is: " & GradeAverage

End Sub