kapela2017
New Member
- Joined
- Oct 16, 2022
- Messages
- 34
- Office Version
- 365
- Platform
- Windows
Greetings, I have a problem relating these two tables, using the "ID" column I did it through a loop, it should take the data from the "Source Table" according to the ID and take it to the "Goal Table", but it only relates the first row the other rows of the "Goal Table" remain in their fields are empty, below I leave the 2 tables and the code any help would be greatly appreciated
[/CODE][/CODE]
SolutionXLookup.xlsm | ||||||
---|---|---|---|---|---|---|
A | B | C | D | |||
1 | ID | PRODUCT | WEIGHT | COST | ||
2 | 1001 | APPLE | 0,2 KG | 2,3$ | ||
3 | 1002 | PEAR | 4,5 KG | 3,1$ | ||
4 | 1003 | PEACH | 5.4 KG | 2,1$ | ||
5 | 1004 | STRAWBERRY | 2,9 KG | 3,4$ | ||
6 | 1005 | CANTAOLUPE | 49 KG | 4,1$ | ||
7 | 1006 | MANGO | 2.4 KG | 3,2$ | ||
8 | 1007 | ORANGE | 5,9 KG | 1,4$ | ||
9 | 1008 | Banana | 8,5 KG | 3,2$ | ||
SourceData |
SolutionXLookup.xlsm | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|
A | B | C | D | E | F | G | H | |||
1 | ID | PRODUCT | WEIGHT | COST | ||||||
2 | 1007 | APPLE | 5,9 KG | 1,4$ | ||||||
3 | 1002 | PEAR | ||||||||
4 | 1003 | PEACH | ||||||||
5 | 1004 | STRAWBERRY | ||||||||
6 | ||||||||||
7 | ||||||||||
8 | ||||||||||
9 | ||||||||||
10 | ||||||||||
GoalTable |
VBA Code:
[CODE=vba][CODE=vba]Option Explicit
Sub CopyData()
Dim wsSourceData As Worksheet
Dim wsGoalTable As Worksheet
Set wsSourceData = ThisWorkbook.Sheets("SourceData")
Set wsGoalTable = ThisWorkbook.Sheets("GoalTable")
Dim SrcTable As ListObject
Set SrcTable = wsSourceData.ListObjects("Source") 'rename
Dim GoalTable As ListObject
Set GoalTable = wsGoalTable.ListObjects("Goal")
Dim a As Object
Dim b As Object
Dim SrcLen As Integer
Dim CounterSrc As Integer
Dim CounterGoal As Integer
SrcLen = SrcTable.ListColumns("ID").DataBodyRange.Rows.Count
CounterSrc = 1
CounterGoal = 1
For Each a In GoalTable.ListColumns("ID").DataBodyRange
For Each b In SrcTable.ListColumns("ID").DataBodyRange
If Str(a) = Str(b) Then
GoalTable.DataBodyRange(CounterGoal, 3).Value = SrcTable.DataBodyRange(CounterSrc, 3).Value 'Weight
GoalTable.DataBodyRange(CounterGoal, 4).Value = SrcTable.DataBodyRange(CounterSrc, 4).Value 'Cost
End If
CounterSrc = CounterSrc + 1
Next
CounterGoal = CounterGoal + 1
Next
End Sub