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