简体   繁体   中英

Excel to match the values within two worksheets

i need a macro/formula to compare the two cell range in a worksheet and return the corresponding value in the cell.

eg sheet: in worksheet 1(sheet1)

AGE Description proof
1   8   
2   9   
3   2   
4   9   
5   5   
6   6   
7   0   
8   1   
9   2   
10  1   

sheet2:

dates   1st 2nd 3rd 4th 5th 6th

0         1  1  2   2   3   3
1         2  3  5   6   7   8   
3         4  6  7   8   9   7 
5         6  7  8   9   10  11
7         8  9  10  11  12  13
10       11 12  13  15  16  18
12       13 15  16  18  19  21
15       16 30  31  45  46  60
30       31 33  34  37  38  40

from the above example if my range needs my expectation (eg in sheet1 Age: 1 and description: 8 then it should compare it with sheet2 and paste the value as 6th in sheet1 proof column). like these i need to fill all the fields

As far as I understand your problem, you are

  1. first matching sheets1.age with sheets2.dates and if you found a match then
  2. You are searching Sheets1.description in sheets2.1st to Sheets2.6th and if you found a mtach then
  3. You are selecting selecting *th(column name) from sheet2 and putting it into sheets1.proof.

I found only 1 match ie for the first observation

Below is the code

Sub checkNmatch()

Calculating the lastrow of sheet1 and sheet2 for automation

lastRowSheet1 = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
lastRowSheet2 = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To (lastRowSheet1 - 1)
 For j = 2 To (lastRowSheet2 - 1)

Checking below if sheets1.age matches with sheets2.dates

   If Worksheets("Sheet1").Cells(i, 1) = Worksheets("Sheet2").Cells(j, 1) Then

If match found then searching Sheets1.description in sheets2.1st to Sheets2.6th

   For k = 2 To 7
   If Worksheets("Sheet1").Cells(i, 2) = Worksheets("Sheet2").Cells(j, k) Then

If match found then copying the column name of Sheet2 into Proof of sheet1

      Worksheets("Sheet1").Cells(i, 3) = Worksheets("Sheet2").Cells(1, k)       
   End If
          Next
        End If
     Next
    Next
    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