我正在寻找一种更简单的if(searchNum - result)< 0,结果将使用数组内较小的值。例如 9000-10000 = -1000,因为结果为负,它将使用数组内的较低变量... 9000-7083 = 1917
此代码正常运行,但无论如何只是它吗?
Dim numbers(), arrItem, maxItem, result, searchNum, minItem
For x = 5 To 10
'search number
searchNum = Cells(x, 3) - Cells(x, 4)
numbers = Array(1, 4167, 4583, 5417, 7083, 10000, 14583, 25000)
'get max of array item
maxItem = Application.Max(numbers)
'loop through each array item
For Each arrItem In numbers
If Abs(searchNum - arrItem) < maxItem Then
maxItem = Abs(searchNum - arrItem)
result = arrItem
If (searchNum - result) < 0 Then
If result = 25000 Then
Cells(x, 6) = searchNum - 14583
ElseIf result = 14583 Then
Cells(x, 6) = searchNum - 10000
ElseIf result = 10000 Then
Cells(x, 6) = searchNum - 7083
ElseIf result = 7083 Then
Cells(x, 6) = searchNum - 5417
ElseIf result = 5417 Then
Cells(x, 6) = searchNum - 4583
ElseIf result = 4583 Then
Cells(x, 6) = searchNum - 4167
ElseIf result = 4167 Then
Cells(x, 6) = searchNum - 1
End If
End If
End If
Next arrItem
Next
提前感谢
答案 0 :(得分:2)
在排序数组中搜索最接近的较低值是VLOOKUP / HLOOKUP在使用TRUE作为最后一个参数时所执行的操作。
VBA中的Array函数生成一个&#34; Horizontal&#34; 1维数组,因此您可以使用HLOOKUP查找最接近searchNum的较低值。
您只需要首先检查以处理searchNum小于引发错误的数字中的最小值的情况。之后,您可以直接分配结果:
Cells(x,6) = searchNum - WorksheetFunction.HLookup(searchNum, numbers, 1, 1)