我试图做一个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 :(得分:1)
如果您更改此行:
Set Table2 = Sheet1.Range("A2:D" & LastRow)
为:
Set Table2 = sourceSheet.Range("A2:D" & LastRow)
您的代码将正常工作
您还应该在每个模块的顶部添加Option Explicit以强制进行变量声明。 cl
未被声明为Range
!