We have two worksheets.
- Source worksheet is “profes”
- Target worksheet is “primaria”
The data common to both worksheets is the name column.
ie: David Smith Weston appears in both worksheets.
We need to “lookup” each students name and paste values from “profes” to “primaria”. I have most of the code working already BUT I don’t know how to add the “lookup” part. As you can see it’s wrong.
Sub Button1_Click() Set Source = ActiveWorkbook.Worksheets("profes") Set Target = ActiveWorkbook.Worksheets("primaria") j = 1 ' Start copying to row 1 in target sheet For Each c In Source.Range("N5:R1000") ' Do 100 rows **If Source.Cells(j, "C").Value = Target.Cells(j, "A").Value** Then Target.Cells(j, "N").Value = Source.Cells(j, "D").Value j = j + 1 End If Next c End Sub
When comparing 2 ranges between 2 worksheets, you have 1
For loop, and replace the second loop with the
Once you loop over your “profes” sheet’s range, and per cell you check if that value is found within the second range in “primaria” sheet, I used
LookupRng, as you can see in the code below – you will need to adjust the range cording to your needs.
Option Explicit Sub Button1_Click() Dim Source As Worksheet, Target As Worksheet Dim MatchRow As Variant Dim j As Long Dim C As Range, LookupRng As Range Set Source = ActiveWorkbook.Worksheets("profes") Set Target = ActiveWorkbook.Worksheets("primaria") ' set up the Lookup range in "primaria" sheet , this is just an example, modify according to your needs Set LookupRng = Target.Range("A2:A100") For Each C In Source.Range("N5:R1000") ' Do 100 rows If Not IsError(Application.Match(C.Value, LookupRng, 0)) Then ' Match was successfull MatchRow = Application.Match(C.Value, LookupRng, 0) ' get the row number from "primaria" sheet where match was found Target.Cells(C.Row, "N").Value = Source.Cells(MatchRow, "D").Value End If Next C End Sub
Use the worksheet’s MATCH function to locate names from the source column C in the target’s column A.
Your supplied code is hard to decipher but perhaps this is closer to what you want to accomplish.
Sub Button1_Click() dim j as long, r as variant dim source as worksheet, target as worksheet Set Source = ActiveWorkbook.Worksheets("profes") Set Target = ActiveWorkbook.Worksheets("primaria") with source for j = 5 to .cells(.rows.count, "C").end(xlup).row r=application.match(.cells(j, "C").value2, target.columns("A"), 0) if not iserror(r) then target(r, "D").resize(1, 5) = .cells(j, "N").resize(1, 5).value end if next j end with End Sub