我在VBA中有以下功能:
Function weightedAverage(x0, y0, x1, y1, x)
weightedAverage = y0 + (x - x0) * (y1 - y0) / (x1 - x0)
End Function
Function interpolateLookup(lookupVal As Range, lookupRange As Range, colID As Integer) As Double
step = 0.01
x0 = Application.Round(lookupVal.Value, 3)
y0 = Application.VLookup(x0, lookupRange, colID, True)
x1 = Application.Round(lookupVal.Value, 3) + step
y1 = Application.VLookup(x1, lookupRange, colID, False)
x = lookupVal.Value
interpolateLookup = weightedAverage(x0, y0, x1, y1, x)
End Function
这里的问题是我的interpolateLookup函数返回一个#VALUE!我传递以下输入时出错:
=interpolateLookup(E5,K3:O803,5)
为什么???
真正的问题在我脑海里。通过利用我的查找键的精度找到了一个解决方案:
Function interpolateLookup(lookupVal As Range, lookupRange As Range, colID As Integer) As Double
step = 0.01
x0 = Application.Round(lookupVal.Value, 2)
y0 = Application.VLookup(x0, lookupRange, colID, False)
x1 = Application.Round(lookupVal.Value, 2) + step
y1 = Application.VLookup(x1, lookupRange, colID, False)
x = lookupVal.Value
interpolateLookup = Application.Round(weightedAverage(x0, y0, x1, y1, x), 1)
End Function
我的lookupVal具有3位数的精度,我的查找键具有2位数的精度,因此我将lookupVal四舍五入为2位,知道我将在表中具有完全匹配,并且还知道它将是我的较低频段插值。
感谢您的评论!