简体   繁体   中英

Error while using Vlookup

I have two sheets , Reason and Lastweek

I would like to compare the column B of both the sheet, if they have the same ID then, I would like to get all the details of lastweek sheet from column 33 to 50 in reasons sheet.

I am able to get the ouput, the problem is , for eg. if I have the data in column 34 of my lastweek sheet, then it is getting entered in column 33 of reason sheet.

Can someone help, how I can overcome this.

Sub lookupUpdate()
Dim BWlRow As Long, CWlRow As Long, i As Long
Dim sformula As String
Dim wsBW As Worksheet, wsCW As Worksheet
Set wsBW = Sheets("Reason"): Set wsCW = Sheets("Lastweek")
BWlRow = wsBW.Cells(wsBW.Rows.count, "A").End(xlUp).Row
CWlRow = wsCW.Cells(wsCW.Rows.count, "A").End(xlUp).Row
For i = 33 To 50 '~~> Col AD to AU
sformula = "=IF(IFERROR(VLOOKUP($B2,Lastweek!$B$2:$AZ" & _
CWlRow & _
"," & _
i & _
",FALSE),""0"")=0,"" "",IFERROR(VLOOKUP($B2,Lastweek!$B$2:$AZ" & _
CWlRow & _
"," & _
i & _
",FALSE),""""))"
With wsBW
With .Range(.Cells(2, i), .Cells(BWlRow, i))
.Formula = sformula
.Value = .Value
End With
End With
Next i
End Sub

Using your example of column number 33, your Vlookup is looking at a range starting from cell B2 in the LastWeek sheet. The 33rd column of this range will be column AH of the sheet. When you are outputting your formula you are outputting into the i th column of the Reason sheet. where i is 33 this is column AG. If you want to output into column AH (column number 34, or i + 1). You can do this by simply changing this line:

With .Range(.Cells(2, i + 1), .Cells(BWlRow, i + 1))

Since the region you are searching using VLOOKUP in is based at B2 instead of A2, you need to subtract 1 from the column offset given to VLOOKUP.

See first example in "How to get started" section. Here the offset is 3, even though looking for data in column D (the Part Price).

https://support.office.com/en-us/article/VLOOKUP-function-0bbc8083-26fe-4963-8ab8-93a18ad188a1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM