简体   繁体   中英

Loop Vlookup “for each cell in range” from another worksheet

I'm trying to loop Vlookup using "for each cell in range" from another worksheet but all lookup_value is getting results even though it doesn't MATCH with the data from table_array.

Here's a sample table & code.

table_array

When IN button was clicked, I want the quantity from each cell of table_array to add the quantity in corresponding lookup_value cells.

Private Sub cmdIN_Click()
Dim rng As Range, cell As Range
Set rng = Sheet2.Range("prodDesc")

 If MsgBox("Are you sure you want to update the stock IN quantity?", vbQuestion + vbYesNo, "Fresh Herbs & Spices") = vbNo Then
  Cancel = True
 End If
 
Application.EnableEvents = False
Application.ScreenUpdating = False
Sheet2.Unprotect Password:=""

On Error Resume Next 'on error run code on next line
 For Each cell In rng
  cell.Offset(, 12).Value = [VLookup(prodDesc, descTable, 2, False)] + cell.Offset(, 12).Value
 Next cell
 
Sheet2.Protect Password:="", DrawingObjects:=True, Contents:=True, Scenarios:=True
Cells(Rows.Count, "C").End(xlUp).Offset(3).Select

Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub

However the result is NOT as expected, because all cells in lookup_value worksheets are getting same result with or without MATCH.

lookup_value

By the way, prodDesc and descTable are dynamic table as range. dynamic tables

After doing some research & asking questions, Here's a working code:

Private Sub cmdIN_Click()
Dim cell As Range, qty

If MsgBox("Are you sure you want to update the stock IN quantity?", vbQuestion + vbYesNo, "Fresh Herbs & Spices") = vbYes Then
  Application.EnableEvents = False
  Application.ScreenUpdating = False
  Sheet2.Unprotect Password:=""

  For Each cell In Sheet2.Range("prodDesc")
    qty = Application.VLookup(cell.Value, Range("descTable"), 2, False)
    If Not IsError(qty) Then cell.Offset(, 13).Value = qty + cell.Offset(, 13).Value
  Next cell
 
  Sheet2.Protect Password:="", DrawingObjects:=True, Contents:=True, Scenarios:=True
  Cells(Rows.Count, "C").End(xlUp).Offset(3).Select

  Application.ScreenUpdating = True
  Application.EnableEvents = True
End If
End Sub

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