VBA如何找到最接近的号码

时间:2016-04-22 09:40:49

标签: excel vba range max

我有一个范围(以一定的间隔变化)。对于每次更改,我希望找到最接近0.5的数字,包括上行和下行。所以,例如,如果我有: 0.42 0.48 0.51 0.53

我想抓住0.48和0.51。

现在我有了这段代码:

 Set Rng = Sheet1.Range("L" & FirstRow & ":L" & RangeCount)
 MaximumInRange = WorksheetFunction.Max(Rng)

我正在计算范围内的最大值,但它很无用。我不知道如何获取最大数量< 0.5和最小值> 0.5。

谢谢!

2 个答案:

答案 0 :(得分:2)

这可能会有所帮助:

 {
      "id": 0,
      "category": {
        "id": 0,
        "name": "string"
      },
      "name": "doggie",
      "photoUrls": [
        "string"
      ],
      "tags": [
        {
          "id": 0,
          "name": "string"
        }
      ],
      "status": "available"
    }

将测试数据放在A1:A4中,如果我运行:

Function BestStraddle(R As Range, target As Double) As Variant
    'Returns a variant array which consists
    'of the largest value < target and
    'smallest value > target

    Dim c As Range
    Dim v As Variant, lower As Variant, upper As Variant

    For Each c In R.Cells
        v = c.Value
        If v < target Then
            If IsEmpty(lower) Then
                lower = v
            ElseIf lower < v Then
                lower = v
            End If
        ElseIf v > target Then
            If IsEmpty(upper) Then
                upper = v
            ElseIf upper > v Then
                upper = v
            End If
        End If
    Next c

    BestStraddle = Array(lower, upper)

End Function

然后将0.48和0.51打印到即时窗口。

答案 1 :(得分:1)

您只需要遍历该范围,并通过检查确定数字是否符合您的标准,而不是最后一个:

Dim Cl As Range

' Arbitrarily set min and max values (maybe replace this with the min and max values of the range):
MinVal = 0
MaxVal = 100
For Each Cl In Rng
  If 0.5 - Cl < 0.5 - MinVal And Cl < 0.5 Then MinVal = Cl
  If Cl - 0.5 < MaxVal - 0.5 And Cl > 0.5 Then MaxVal = Cl
Next Cl

' Output the values however you need them:
Debug.Print MinVal
Debug.Print MaxVal