我们在做数据分析时,经常会遇到数据匹配的问题,我们常用的数据匹配的函数有:VLOOKUP、HLOOKUP、XLOOKUP、index+match等等。大部分的数据查找和匹配问题都能通过以上函数解决。但是当我们遇到需要查找在某个区域内和目标值最近接的值时,以上函数就显得捉襟见肘了。
此时我们就需要今天所讲到的方法,自定义函数法。
自定义函数实现查找最近的值:
1、遍历指定区域内的每一个单元格
2、计算单元格与目标值相减的绝对值
3、初始判断函数结果是否有值,为空设置为当前迭代的绝对值只差
4、不为空判断当前绝对值之差与之前保存的绝对值之差,如果当前绝对值差更小
5、替换临时保存绝对值,直到所有的单元格都遍历完成
以下为自定义函数代码:
'查找source指定区域内最接近target的值Function Closest(source As Range, target As Range) Dim current As Range For Each current In source tempDiff = Abs(current.Value - target.Value) If IsEmpty(Closest) Then diff = tempDiff Closest = current.Value End If If tempDiff < diff Then Closest = current.Value diff = tempDiff End If NextEnd Function
Function Closest(source As Range, target As Range)
Dim current As Range
For Each current In source
tempDiff = Abs(current.Value - target.Value)
If IsEmpty(Closest) Then
diff = tempDiff
Closest = current.Value
End If
If tempDiff ˂ diff Then
Closest = current.Value
diff = tempDiff
End If
Next
End Function