Excel vba - Application.Index返回错误的值

时间:2015-06-11 16:53:28

标签: excel-vba vba excel

我有一个调用Application.Index的vba函数。 我的问题是,它有时会返回一个在查找范围内不存在的项的值!我有一个isError检查,但它返回false。 在大约150行中,其中30行返回不正确 - 其他120正在返回正确。

如果有人可以提供帮助,我们将不胜感激! 这是我的代码:

Function getQtyOnHand(skuRng As Range, tc As Range, skuCol As Range) As Long
     Dim index, retVal As Long, sku As String
     sku = skuRng.Value
     index = Application.Match(sku, skuCol)
     If IsError(index) Then
       retVal = 0
     Else
       retVal = Application.index(tc, index, 0)
     End If
     getQtyOnHand = retVal
End Function

为清楚起见,以下是发送到此功能的信息:

    Dim totalCol As Range, stockSkuCol As Range
    Set totalCol = wbStock.Worksheets("MAIN").Range("F:F")
    Set stockSkuCol = wbStock.Worksheets("MAIN").Range("A:A")

    getQtyOnHand(ws.Range("F2"), totalCol, stockSkuCol)

进一步测试....这里是一个完全独立的功能,显示错误的输出:

 Sub testIndex()
     Dim wb1 As Workbook, wb2 As Workbook, ws1 As Worksheet, ws2 As Worksheet
     Set wb1 = Workbooks("Output.xlsm")
     Set wb2 = Workbooks("STOCK.xlsx")
     Set ws1 = wb1.Worksheets("StockList")
     Set ws2 = wb2.Worksheets("MAIN")

     Dim c1 As Range
     Set c1 = ws1.Range("D131")

     Dim ind
     ind = Application.WorksheetFunction.Match(c1.Value, ws2.Range("A:A"))

     Debug.Print (c1.Value & " was found in row " & ind & " whose value is " & ws2.Range("A" & ind))

 End Sub

debug.print输出为:

ZM-101 was found in row 100 whose value is YK21222L

!! ???? (顺便说一下,100是本文档的最后一行)

谢谢,戴维

1 个答案:

答案 0 :(得分:2)

您对Match的来电未指定搜索类型。您只使用2个参数调用它,默认为1。您希望使用0显式调用它以获得完全匹配。通过在普通电子表格中使用公式版本来查看最终参数的效果,可以更好地理解这一点。

修正:

index = Application.Match(sku, skuCol, 0)

您稍后致电Application.WorksheetFunction.Match(..,..)

的同一故事