My code looks at a table with three different Ids and a qty. It sums all rows where the three ids are the same and pastes it sheet2. The original table is always sorted with the three Id columns sorted in alphabetical order.
Original Table
+--------+------+---------+-----+
| Name | City | Country | Qty |
+--------+------+---------+-----+
| Jack | A | US | 15 |
| Jack | A | US | 16 |
| Kevin | A | US | 12 |
| Kevin | A | US | 11 |
| Jack | B | US | 13 |
| Jack | B | US | 10 |
+--------+------+---------+-----+
Output Table
+--------+------+---------+-----+
| Name | City | Country | Qty |
+--------+------+---------+-----+
| Jack | A | US | 31 |
| Kevin | A | US | 23 |
| Jack | B | US | 23 |
+--------+------+---------+-----+
Code
For i = 2 To totalrow 'totalrow is the total number of rows
name = sheet1.Cells(i, 1)
city = sheet1.Cells(i, 2)
country = sheet1.Cells(i, 3)
qty = 0
Do
qty = qty + sheet1.Cells(i, 4)
i = i + 1
Loop While wsDB.Cells(i, 1) = name And wsDB.Cells(i, 2) = city And wsDB.Cells(i, 3) = country
sheet2.Cells(process_row, 1).Value = name
sheet2.Cells(process_row, 2).Value = city
sheet2.Cells(process_row, 3).Value = country
sheet2.Cells(process_row, 4).Value = qty
process_row = process_row + 1
i = i - 1
Next I
I timed how long the code took to run and it consistently takes 30 seconds. I then removed the section pasting the updated values into sheet2 and timed it (code below). That consistently took less than 1 second.
For i = 2 To totalrow
bl = wsDB.Cells(i, 1)
cpty = wsDB.Cells(i, 2)
cptyname = wsDB.Cells(i, 3)
cusip = wsDB.Cells(i, 4)
qty = 0
Do
qty = qty + wsDB.Cells(i, 6)
i = i + 1
Loop While wsDB.Cells(i, 1) = bl And wsDB.Cells(i, 2) = cpty And wsDB.Cells(i, 4) = cusip
process_row = process_row + 1
i = i - 1
Next i
It appears that inserting cell values requires the most time. Are there any methods in which I can speed this up?