具有Vlookupfunction的VBA

我有两张纸,Sht1和Sht2。 用sht1,我总是看看B列,检查ID是否与sht2的B列匹配,如果匹配,那么我把sht1的列Q值复制到sht2。

我试着通过下面的代码完成,我无法得到结果,代码中没有显示错误。

我迷失了我的代码有什么问题。 任何人都可以帮我摆脱这一点。

Sub vlookupComments() Dim totalrows As Long, totalrowsSht2 As Long Dim ws As Worksheet totalrows = Sheets("sht1").Cells(Rows.Count, "A").End(xlUp).Row totalrowsSht2 = Sheets("sht2").Cells(Rows.Count, "A").End(xlUp).Row Sheets("sht1").Range("Q5:Q" & totalrows).Formula = Application.WorksheetFunction.IfError(Application.VLookup(Sheets("sht1").Range("B5:B" & totalrowsSht2), Sheets("sht2").Range("$A:$Q"), 17, 0), "") End Sub 

你的问题是“将sht1的列Q值复制到sht2”,而公式则是另一种方式。 我去配方,

试试下面的macros,

 Sub vlookupComments() Dim totalrows As Long, totalrowsSht2 As Long Dim ws As Worksheet totalrows = Sheets("sht1").Cells(Rows.Count, "A").End(xlUp).Row totalrowsSht2 = Sheets("sht2").Cells(Rows.Count, "A").End(xlUp).Row For i = 1 To totalrows Sheets("sht1").Cells(i, "Q").Value = _ Application.WorksheetFunction.VLookup(Sheets("sht1").Cells(i, "B"), _ Sheets("sht2").Range("A1:Q" & totalrowsSht2), 17, 0) Next i End Sub 

选项2:

 Sub lookupmaturitystart() Dim totalrows As Long, totalrowsSht2 As Long totalrows = Sheets("Maturity_BU").Cells(Rows.Count, "A").End(xlUp).Row totalrowsSht2 = Sheets("Maturity_Lastweek").Cells(Rows.Count, "A").End(xlUp).Row For i = 5 To totalrows For j = 1 To totalrowsSht2 If Sheets("Maturity_BU").Cells(i, "B") = Sheets("Maturity_Lastweek").Cells(j, "B") Then Sheets("Maturity_BU").Cells(i, "Q") = Sheets("Maturity_Lastweek").Cells(j, "Q") End If Next j Next i End Sub 

尝试下面的代码

 Sheets("sht1").Range("Q5:Q" & totalrows).Value = "=IFERROR(VLOOKUP(B5,Sheet2!$A:$Q,17,0),"""")"