2017-02-26 412 views
0

我試圖做一個Vlookup,但它返回錯誤2042,即使有匹配。我無法弄清楚代碼有什麼問題。任何幫助將不勝感激。Excel VBA Vlookup返回 - 錯誤2042

Private Sub F6P_SORT() 

Dim targetWorkbook As Workbook 
Dim sourceSheet As Worksheet 
Dim targetSheet As Worksheet 
Dim LastRow As Long 

Set targetWorkbook = Application.ActiveWorkbook 
Set targetSheet = targetWorkbook.Worksheets("MTD") 

On Error Resume Next 
Dim Table1 As Range 
Dim Table2 As Range 
Dim Table3 As Range 

Dim IniName_Row As Long 
Dim IniName_Clm As Long 

LastRow = targetSheet.Range("A65536").End(xlUp).Row 
Set Table1 = targetSheet.Range("A2:A" & LastRow) ' CC/IO from MTD 
Set Table3 = targetSheet.Range("F2:F" & LastRow) ' Ini Name to MTD 

Set sourceSheet = targetWorkbook.Worksheets("IO Lookup") 
LastRow = sourceSheet.Range("A65536").End(xlUp).Row 
Set Table2 = Sheet1.Range("A2:D" & LastRow) ' IO from IO Lookup 


IniName_Row = Table3.Row 
IniName_Clm = Table3.Column 

For Each cl In Table1 
    targetSheet.Cells(IniName_Row, IniName_Clm) = Application.VLookup(cl, Table2.Value, 4, False) 
    IniName_Row = IniName_Row + 1 
Next cl 

End Sub 
+0

哪裏出錯?在'for each cl'循環中的'targetSheet.Cells(...'行)? – BruceWayne

+1

從VLookup中的Table2.Value中移除'.Value',它需要的範圍不是範圍的值。 –

+0

錯誤發生在「targetSheet.Cells(IniName_Row,IniName_Clm)= Application.VLookup(cl,Table2.Value,4,False)」 – user7626448

回答

1

如果改變這一行:

Set Table2 = Sheet1.Range("A2:D" & LastRow) 

到:

Set Table2 = sourceSheet.Range("A2:D" & LastRow) 

您的代碼將工作

您還應該添加選項明確到每一個模塊的頂部強制變量聲明。 cl尚未宣佈爲Range