如何将variables值向下舍入到数组中的下一个最小数字?

我正在使用VBA在Excel中处理macros。 我有一系列的数字,如:

180, 190, 300, 390, 400, 430, ... 

然后,我有一个值为307389425的variables。 我怎样才能将这个数字下降到数组中包含的下一个最低的数字,而不使用一堆If语句?

例如,我需要改变:

 307 -> 300 389 -> 300 425 -> 400 

比使用一长串逻辑语句更快的方法是做什么?

如果你的数组是sorting的,你可以使用HLOOKUP() 。 如果您为最后一个参数指定了True ,它将匹配最近的前一个值。 例如:

 Debug.Print WorksheetFunction.HLookup(307, Array(180, 190, 300, 390, 400, 430), 1, True) 

输出:

 300 

你只需要防止less于最低数字(在这种情况下为180)的数字。 所以你可能想用数值0开始你的数组。

假设数组是sorting的,你可以使用:

 Function RoundTo(A As Variant, num As Long) As Variant 'returns greatest number in A which is <= num 'returns False if no such number exists 'assumes A is a sorted array of numbers Dim i As Long On Error Resume Next i = Application.WorksheetFunction.Match(num, A, 1) If Err.Number > 0 Then RoundTo = False Exit Function End If On Error GoTo 0 RoundTo = A(LBound(A) + i - 1) End Function 

用于:

 Sub test() Dim A As Variant, i As Long A = Array(12, 15, 19, 25, 39) Debug.Print RoundTo(A, 45) Debug.Print RoundTo(A, 18) Debug.Print RoundTo(A, 12) Debug.Print RoundTo(A, 11) End Sub 

输出:

  39 15 12 False 

当然,当数字太小而无法四舍五入到数字列表中的任何数字时,您可以调整它以返回False以外的内容

你可以做这样的事情。

 Private Sub CommandButton20_Click() Dim aValues(1 To 5) As Integer Dim i As Integer aValues(1) = 180 aValues(2) = 190 aValues(3) = 300 aValues(4) = 390 aValues(5) = 400 Dim iFindValue As Integer iFindValue = 310 'First make sure we have a valid value to check for. If aValues(1) > iFindValue Then MsgBox ("Lowest value in the array is greater than variable.") Exit Sub End If 'Loop through the array For i = 1 To UBound(aValues) 'If we are at the end of the array, we haven't found it so set the value to the highest slot in the array. If i = UBound(aValues) Then iFindValue = aValues(i) Exit Sub End If 'If it is in between the current slot value and the next one, set it to the current. Effectively rounding it down. If aValues(i) < iFindValue And aValues(i + 1) > iFindValue Then iFindValue = aValues(i) Exit Sub End If Next i End Sub 

你说你的数组可以被sorting,但如果由于某种原因没有,你可以做这样的事情。

 Private Sub CommandButton20_Click() Dim aValues(1 To 5) As Integer Dim i As Integer aValues(1) = 180 aValues(2) = 190 aValues(3) = 300 aValues(4) = 390 aValues(5) = 400 Dim iFindValue As Integer iFindValue = 310 Dim iTemp As Integer Dim iDifference As Integer iDifference = 32000 For i = 1 To UBound(aValues) 'Find the difference iTemp = iFindValue - aValues(i) 'If it is the smallest difference found so far, record it If iTemp > 0 And iTemp < iDifference Then iDifference = iTemp End If Next i 'Make the adjustment iFindValue = iFindValue - iDifference End Sub