WorksheetFunction.Match无法正常工作

时间:2014-05-09 20:24:03

标签: excel vba excel-vba match

以下是我的数据摘录:

------+------+------+------+------+
      |  A   |  B   |  C   |  D   |
------+------+------+------+------+
1     | 10      20     25     30
2     | 152    181    195    210

和我的代码:

Dim xrng as range, yrng as range, offset as integer

set xrng = Sheets("Sheet1").Range("A1:D1")
set yrng = Sheets("Sheet1").Range("A2:D2")

offset = WorksheetFunction.Match(23, xrng , 1) - 1

为什么运行此结果会导致1004错误:Unable to get the match property of the worksheetfunction class?我该如何解决?


编辑:详细问题

好的,我编写了一个插值函数:

Public Function interpolate(intvalue_X As Double, xrange As range, yrange As range) As Double
....this is just an excerpt:
    Dim offst As Integer
    offst = WorksheetFunction.Match(intvalue_X, xrange, 1) - 1 'find the offset of the nearest value
---
End Function

使用以下数据和调用,它可以正常工作并返回正确的答案: (不要介意变量'谁的声明没有显示 - 它们已经在此时被声明,它只是没有被复制)

enter image description here

Set intXrng = Sheets("Tables").range("B32:G32")
    If beltWidth >= 46 And beltWidth <= 122 And conveyerCenter >= 7.6 And conveyerCenter <= 152.4 Then 'dan kan jy die tabel gebruik
    m = interpolate(beltWidth, intXrng, Sheets("Tables").range("B44:G44"))
    c = interpolate(beltWidth, intXrng, Sheets("Tables").range("B45:G45"))
    powerX = m * conveyerCenter + c
Else
    MsgBox "Unable to use the power x-factor table.", vbCritical
End If

现在,当我使用相同的函数,但是使用这个数据和调用时,它会给出错误:

enter image description here

Set intXrng = Sheets("Tables").range("F4:I4")
angleSurcharge = 23
capacityTable = interpolate(angleSurcharge, intXrng, Sheets("Tables").range("F7:I7"))

1 个答案:

答案 0 :(得分:1)

您的值不会存储为字符串,因为它们位于表头中。无论格式如何,表头都始终被读取为字符串。

您可以将所有值转换为双打,然后再将其传递给Worksheet.Match以修复错误。

Dim offst As Integer
Dim arry As Variant
ReDim arry(1 To 1, 1 To xrange.Columns.Count)

For i = 1 To xrange.Columns.Count
    arry(1, i) = CDbl(xrange.Cells(1, i).Value)
Next
offst = WorksheetFunction.Match(intvalue_X, arry, 1) - 1    'find the offset of the nearest value