【问题标题】:#Value error using custom function in Excel#在Excel中使用自定义函数的值错误
【发布时间】:2017-08-31 11:31:25
【问题描述】:

我在尝试调用自定义函数时收到 #VALUE 错误。它应该做的只是一点数学。有人知道这里有什么问题吗?

我从网上复制了这个:

来源:

http://www.engineerexcel.com/linear-interpolation-vba-function-in-excel/

Function LININTERP(x, xvalues, yvalues)

'x and y values must be in ascending order from top to bottom.
'x must be within the range of available data.

x1 = Application.WorksheetFunction.Index(xvalues, Application.WorksheetFunction.Match(x, xvalues, 1))
x2 = Application.WorksheetFunction.Index(xvalues, Application.WorksheetFunction.Match(x, xvalues, 1) + 1)

y1 = Application.WorksheetFunction.Index(yvalues, Application.WorksheetFunction.Match(x, xvalues, 1))
y2 = Application.WorksheetFunction.Index(yvalues, Application.WorksheetFunction.Match(x, xvalues, 1) + 1)

LININTERP = y1 + (y2–y1) * (x–x1) / (x2–x1)
End Function

这是我认为工作表函数调用可能导致错误的简化版本:

Function LININTERP(x, x1, x2, y1, y2)
  LININTERP = y1 + (y2–y1) * (x–x1) / (x2–x1)
End Function

我在不相关工作簿中的测试数据: (全部格式化为“常规”)

A1: 633
A2: 634
B1: 14.968
B2: 15.024
C1 (my x): 633.6

只需将实际数学插入单元格即可按预期工作。调用该函数会引发 #VALUE 错误。

我的函数保存在我已保存并作为加载项添加到 Excel 的工作簿的模块中。

【问题讨论】:

  • 您的 - 不是实际的减号,代码 150 与代码 45。突出显示每个并用实际输入的 - 替换它
  • 顺便说一句,如果 VBE 识别出数学运算,那些(y2–y1)应该自动更正为(y2 - y1)
  • 同样使用 Option Explicit 会出现编译错误(变量未定义)

标签: excel function add-in user-defined-functions vba


【解决方案1】:

我对您的公式和数据的抽样在连字符未被解释为“减号”时出现了错误。事实上,它们以 unicode 8211 的形式出现。重新键入它们,将变量声明为变体并删除 ...WorksheetFunction... 解决了问题。

Function LININTERP(x, xvalues, yvalues)
    Dim x1 As Variant, x2 As Variant, y1 As Variant, y2 As Variant

    'x and y values must be in ascending order from top to bottom.
    'x must be within the range of available data.

    x1 = Application.Index(xvalues, Application.Match(x, xvalues, 1))
    x2 = Application.Index(xvalues, Application.Match(x, xvalues, 1) + 1)

    y1 = Application.Index(yvalues, Application.Match(x, xvalues, 1))
    y2 = Application.Index(yvalues, Application.Match(x, xvalues, 1) + 1)

    LININTERP = y1 + (y2 - y1) * (x - x1) / (x2 - x1)
End Function

故事的寓意:不要相信你在互联网上找到的一切。

【讨论】:

  • btw² - 删除 WorksheetFunction 并将返回值传递回一个变体允许您检查像 If IsError(x1) Then 这样的错误。保留 WorksheetFunction 会消除这种错误处理能力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多