2014-02-19 103 views
0

我試圖使用VLOOKUP來檢查我的變量是否出現在listobject中,如果是這樣,則檢索相應的值。在VLOOKUP中使用變量

我的代碼總是轉到在以下行雖然錯誤:

shtData.Cells(rowNumber, perf1).Value = wsFunc.IfError(wsFunc1.VLookup(shtData.Cells(rowNumber, cep1).Value, perfTable, 2, False), Null) 

我的代碼如下:

Dim wb As Workbook 
Set wb = ActiveWorkbook 
Dim wsFunc As WorksheetFunction 
Set wsFunc = Application.WorksheetFunction 
Dim wsFunc1 As WorksheetFunction 
Set wsFunc1 = Application.WorksheetFunction 
Dim cep As Variant 
Dim perfTable As ListObject 
Set perfTable = perfData.ListObjects("PerfTable") 
Dim cepTable As ListObject 
Set cepTable = perfData.ListObjects("cepTable") 

perfCol = perfTable.ListColumns("Column1").Index 
perfSort = perfTable.ListColumns("Column2").Index 
cepCol = cepTable.ListColumns("Column1").Index 
cepSort = cepTable.ListColumns("Column2").Index 

On Error GoTo errHandler 

Set usedRange = returnUsedRange(shtData, wb) 
Set perfRange = returnUsedRange(perfData, wb) 
Set cepRange = returnUsedRange(perfData, wb) 

For Each Row In usedRange 
    For Each sec In secRange 
     rowNumber = Row.Row 
     secRow = sec.Row 
      shtData.Cells(rowNumber, perf1).Value = wsFunc.IfError(wsFunc1.VLookup(shtData.Cells(rowNumber, cep1).Value, perfTable, 2, False), Null) 
    Next 
+0

我不認爲你可以像這樣返回null。你可能不得不返回'''''或'0'。這可能有助於包括錯誤所說的內容。 – Bigtree

+0

我試過將它改爲「」相同的結果 – db579

回答

1

不能使用Excel IFERROR函數那樣:

只需使用

x = application.vlookup(...,...,...,...) 

沒有WorksheetFunction使您可以檢查VLOOKUP錯誤...

if iserror(X) then ' vlookup failed (x is variant) 
0

爲什麼不使用這種方法。它的快速和容易實現:

Dim i As Integer 
Dim arrData2Search() As Variant 

Set arrData2Search = Range(Cells(1, 1), Cells(1000, 2000)).value 


    For i = 1 To 2000 
     If arrData2Search (i, 1)= "Target" Then 
      ' your code 
     End If 
    Next i 
+0

對我的要求太慢。這是我不得不從頭開始,工作得很好,但它需要2-3分鐘才能運行,所以我希望VLOOKUP可以提高性能 – db579

+2

vlookup的確會更快:)看到我的回答 – CRondao

+0

對不起,我發佈了錯誤代碼。這個新代碼與VLookUP一樣高效。將整個範圍複製到一個數組並使用數組 – Pedrumj