函数为范围内的每个单元格返回“太低”,“太高”或“OK”

我想要一个函数来运行一系列的单元格,如果:

  • 任何大于NormalValue然后返回“太低”,

  • NormalValue大于范围内的最大值的两倍然后返回“太高”,

  • 这些都不是真的,然后返回“确定”。

这是我到目前为止所提出的:

 Function TooHighLow(rng As range, NormalValue As Double) For Each cell In rng If Application.WorksheetFunction.Max(cell.Value) > NormalValue Then TooHighLow = "Too Low" ElseIf NormalValue > 2 * (Application.WorksheetFunction.Max(cell.Value)) Then TooHighLow = "Too High" Else TooHighLow = "OK" End If Next cell End Function 

我想你想要这样的东西:

 Function TooHighLow(rng As Range, NormalValue As Double) Dim m As Double m = Application.WorksheetFunction.Max(rng) If m > NormalValue Then TooHighLow = "Too Low" ElseIf NormalValue > 2 * m Then TooHighLow = "Too High" Else TooHighLow = "OK" End If End Function 

1)循环是毫无意义的

2)你应该只计算一次最大值,将结果存储在一个variables中。

没有VBA:

 =IF(MAX(range)>NormalValue,"too low",IF(NormalValue>2*MAX(range),"too high","OK")) 

如果您正在尝试从一系列单元格中find单个低点或高点,那么您将不得不接受未完成的值,并在该点退出您的function。 继续循环将覆盖未经处理的范围内的下一个单元格。

 Function TooHighLow(rng As range, NormalValue As Double) dim cell as range 'start with a default value TooHighLow = "OK" For Each cell In rng If Application.WorksheetFunction.Max(cell.Value) > NormalValue Then 'set the function to return Too Low TooHighLow = "Too Low" 'exit the For Next loop Exit For ElseIf NormalValue > 2 * (Application.WorksheetFunction.Max(cell.Value)) Then 'set the function to return Too High TooHighLow = "Too High" 'exit the For Next loop Exit For End If 'if the loop has not been exited, the next cell in the range will be evaluated 'if the loop has been exited, the function will return the outstanding value Next cell End Function