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

我怎样才能做到这一点,而不用在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)" 

如果要直接将公式parsing为双精度型variables,请使用Excel应用程序对象直接调用ROUNDDOWN , ROUNDUP和AGGREGATE函数。

 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 

您将从引号中删除vba部分,并使用&连接string:

 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)")