问题
Multi Criteria Index/Match VBA across two sheets in the same workbook
So, basically, I have 2 sheets in a same workbook
Sheet 1 looks like this:
Sheet 2 looks like this:
I want to match the Comments section based on PO/SO AND Activity using VBA instead of formula.
Below is the code I tried to write, but it’s not working…
Dim ID As String, Activity As String
For r = 2 To ThisWorkbook.Worksheets("Sheet1").UsedRange.Rows.Count
ID = ThisWorkbook.Worksheets("Sheet1").Cells(r, 1).Value
Activity = ThisWorkbook.Worksheets("Sheet1").Cells(r, 2).Value
For s = 2 To ThisWorkbook.Worksheets("Sheet2").UsedRange.Rows.Count
If ThisWorkbook.Worksheets("Sheet2").Cells(s, 1).Value = ID And ThisWorkbook.Worksheets("Sheet2").Cells(s, 2).Value = Activity Then
ThisWorkbook.Worksheets("Sheet2").Cells(s, 3).Value = ThisWorkbook.Worksheets("Sheet1").Cells(s, 3).Value
End If
Next s
Next r
If I try to run the code, I won't get any error warnings, but nothing else would happen neither...no error message, no any reaction. I double checked all names, column numbers, and everything
回答1:
I had no problem with your code except you need to Change this line...
ThisWorkbook.Worksheets("Sheet2").Cells(s, 3).Value = ThisWorkbook.Worksheets("Sheet1").Cells(s, 3).Value
To
ThisWorkbook.Worksheets("Sheet2").Cells(s, 3).Value = ThisWorkbook.Worksheets("Sheet1").Cells(r, 3).Value
回答2:
Hi Emma Assuming your sheet 1 and your sheet 2 have the same column lineup.
Sub findMatch()
Dim ID As String
Dim Activity As String
For r = 2 To ThisWorkbook.Worksheets("Sheet1").UsedRange.Rows.Count
ID = ThisWorkbook.Worksheets("Sheet1").Cells(r, 1).Value
Activity = ThisWorkbook.Worksheets("Sheet1").Cells(r, 2).Value
For s = 2 To ThisWorkbook.Worksheets("Sheet2").UsedRange.Rows.Count
If ThisWorkbook.Worksheets("Sheet2").Cells(s, 1).Value = ID And ThisWorkbook.Worksheets("Sheet2").Cells(s, 2).Value = Activity Then
ThisWorkbook.Worksheets("Sheet2").Cells(s, 4).Value = ThisWorkbook.Worksheets("Sheet1").Cells(s, 3).Value
End If
Next s
Next r
End Sub
This is the code you presented above and it worked just fine for me. I made a minor change to test for myself just on this line.
ThisWorkbook.Worksheets("Sheet2").Cells(s, 4).Value = ThisWorkbook.Worksheets("Sheet1").Cells(s, 3).Value
here is my workbook. sheet 1 and sheet 2. I will caution, however, that looking for a match in this order could be troublesome. I would use much rather use a find function and loop sheet 2.
来源:https://stackoverflow.com/questions/59615083/multiple-criteria-match-index-vba-across-two-sheets