2015-06-11 111 views
0

我有一個調用Application.Index的vba函數。 我的問題是,它有時會返回查找範圍中不存在的項目的值!我有一個isError檢查,但它返回false。 在大約150行中,其中30個返回不正確 - 其他120個返回正確。Excel vba - Application.Index返回錯誤值

如果有人可以幫忙,將不勝感激! 這裏是我的代碼:

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

您對Match打不指定搜索類型。你只用2個參數來調用它,默認爲1。您希望明確地使用0來調用它以獲得完全匹配。通過在普通電子表格中使用公式版本可以更好地理解該最終參數的效果。

修復:

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

您以後調用同樣的故事,以Application.WorksheetFunction.Match(..,..)

+0

謝謝!這是其中的一個錯誤......。我覺得這種情況下,你一直在尋找你的手錶,直到你終於意識到你正在穿着它...... I-我錯誤地把第三個參數放在索引功能中,而不是匹配功能! – DaveyD