公式中使用的值类型错误

时间:2019-04-20 08:35:54

标签: excel vba

我正在调用UDF函数。正在报告#value错误,该错误表示公式中使用的值是错误的数据类型。请在代码下方找到

Function pattern(a As Double, x As Range, y As Range) As Double
    Dim i As Integer, x1 As Double, x2 As Double, y1 As Double, y2 As Double

    For i = 0 To x.RowCount
        If x(i) > a Then GoTo Line1
    Next i

    Line1:
    x1 = x(i - 1)
    x2 = x(i)
    y1 = y(i - 1)
    y2 = y(i)

    pattern = y1 + ((y2 - y1) * (a - x1) / (x2 - x1)) 
End Function

1 个答案:

答案 0 :(得分:0)

尝试一下:

Function Pattern(a As Double, x As Range, y As Range) As Double
    Dim i As Integer, x1 As Double, x2 As Double, y1 As Double, y2 As Double

    For i = 1 To x.Rows.Count
        If x(i) > a Then
            x1 = x(i - 1)
            x2 = x(i)
            y1 = y(i - 1)
            y2 = y(i)

            Pattern = y1 + ((y2 - y1) * (a - x1) / (x2 - x1))
            Exit Function
        End If
    Next i
End Function
  • Range对象(例如xy)不能为零索引。所以i = 1 to x.Rows.Count
  • 我会避免使用GoTo语句,而应使用exit function(退出循环)