Hello everyone and don’t judge me a lot, as I’m not experienced VBA coder just time to time trying to make my life easier and automate some things…
I have 2 tables on 2 sheets and trying to fill T1 with data from T2, if multiple conditions are met…
Test | L1 | L2 | L3 | |||||||
---|---|---|---|---|---|---|---|---|---|---|
A | B | C | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 |
A1 | 1 | C1 | ||||||||
A1 | 2 | C2 | ||||||||
A2 | 3 | C3 | ||||||||
A1 | 4 | C4 |
A | B1 | B2 | B3 | B4 | R | C | L | N |
---|---|---|---|---|---|---|---|---|
A1 | 1 | 2 | 3 | 4 | Test | All | a | 1 |
A1 | 1 | 2 | C1 | b | 2 | |||
A2 | 1 | 2 | C4 | c | 3 | |||
A1 | 3 | d | 4 | |||||
A2 | 1 | 3 | 4 | C2 | e | 5 | ||
A2 | C2 | f | 6 | |||||
A1 | 1 | C2 | g | 7 | ||||
A2 | 2 | h | 8 | |||||
A2 | 3 | C4 | i | 9 | ||||
A2 | C3 | j | 10 | |||||
A1 | 1 | 2 | C1 | k | 11 | |||
A1 | 3 | 4 | C1 | l | 12 |
I’ve managed to get first 2 columns filled but can’t get nth matching values…
some code below:
Sub test()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim a As String
Dim b As String
Dim c As String
Dim f As String
Set sht1 = ThisWorkbook.Worksheets("M")
Set sht2 = ThisWorkbook.Worksheets("S")
For d = 4 To sht1.UsedRange.Rows.count
For e = 3 To sht2.UsedRange.Rows.count
For g = 5 To sht1.UsedRange.Columns.count
a = sht1.Cells(d, 2).Value
b = sht1.Cells(2, g).Value
c = sht1.Cells(d, 3).Value
f = sht1.Cells(d, 4).Value
If sht2.Cells(e, 2).Value = a _
And sht2.Cells(e, 7).Value = b _
And (sht2.Cells(e, 3).Value = c _
Or sht2.Cells(e, 4).Value = c _
Or sht2.Cells(e, 5).Value = c _
Or sht2.Cells(e, 6).Value = c) _
And sht2.Cells(e, 8).Value = "All" _
And sht2.Cells(e, 8).Value <> "" _
Then
sht1.Cells(d, g).Value = sht2.Cells(e, 9).Value
sht1.Cells(d, g + 1).Value = sht2.Cells(e, 10).Value
End If
If sht2.Cells(e, 2).Value = a _
And b = "L1" _
And (sht2.Cells(e, 3).Value = c _
Or sht2.Cells(e, 4).Value = c _
Or sht2.Cells(e, 5).Value = c _
Or sht2.Cells(e, 6).Value = c) _
And sht2.Cells(e, 8).Value = f _
And sht2.Cells(e, 8).Value <> "" _
Then
sht1.Cells(d, g).Value = sht2.Cells(e, 9).Value
sht1.Cells(d, g + 1).Value = sht2.Cells(e, 10).Value
End If
If sht2.Cells(e, 2).Value = a _
And b = "L2" _
And (sht2.Cells(e, 3).Value = c _
Or sht2.Cells(e, 4).Value = c _
Or sht2.Cells(e, 5).Value = c _
Or sht2.Cells(e, 6).Value = c) _
And sht2.Cells(e, 8).Value = f _
And sht2.Cells(e, 8).Value <> "" _
Then
sht1.Cells(d, g).Value = sht2.Cells(e, 9).Value
sht1.Cells(d, g + 1).Value = sht2.Cells(e, 10).Value
End If
Next g
Next e
Next d
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
New contributor
Bambino5 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.