VBA:从范围选择中获取最小值和最大值,同时忽略NA

时间:2016-08-25 16:14:34

标签: excel vba excel-vba

如果不在excel中实际设置范围,我该怎么做?理想情况下,它只是为了计算而内部(和临时)存储在VBA中。显然,当前代码不起作用,因为FormulaArray仅适用于范围对象。

    Dim lower As Double
    lower.FormulaArray = "=RoundDown(Min(If(Not(ISNA(objSelection)), objSelection)), 0)"
    Dim upper As Double
    upper.FormulaArray = "=RoundUp(Max(If(Not(ISNA(objSelection)), objSelection)), 0)"

2 个答案:

答案 0 :(得分:3)

您可以从引号中删除vba部分,并将字符串与&连接在一起:

Dim lower As Double
lower = ActiveSheet.Evaluate("=RoundDown(Min(If(ISNUMBER(" & Selection.Address & "), " & Selection.Address & ")), 0)")
Dim upper As Double
upper = ActiveSheet.Evaluate("=RoundUp(Max(If(ISNUMBER(" & Selection.Address & "), " & Selection.Address & ")), 0)")

答案 1 :(得分:1)

如果要直接将公式解析为double类型变量,请使用Excel Application object直接调用ROUNDDOWNROUNDUPAGGREGATE函数。

Dim lower As Double, upper As Double, objSelection As Range

Set objSelection = Selection

'trim any full row or column selections down to the used range
Set objSelection = Intersect(objSelection.Parent.UsedRange, objSelection)

lower = Application.RoundDown(Application.Aggregate(15, 6, objSelection, 1), 0)
upper = Application.RoundUp(Application.Aggregate(14, 6, objSelection, 1), 0)
Debug.Print lower
Debug.Print upper