Forum Discussion
Consolidate a list based on identical values in one column
- May 17, 2021
Like this:
Sub Transform() Dim wshS As Worksheet Dim wshT As Worksheet Dim s As Long Dim m As Long Dim t As Long Dim c As Long Application.ScreenUpdating = False Set wshS = Worksheets("Current List") Set wshT = Worksheets("Result") wshT.Range("A2:A" & wshT.Rows.Count).EntireRow.Clear m = wshS.Range("A" & wshS.Rows.Count).End(xlUp).Row t = 1 For s = 2 To m If wshS.Cells(s, 1).Value <> wshS.Cells(s - 1, 1).Value Then t = t + 1 wshT.Cells(t, 1).EntireRow.NumberFormat = "@" wshT.Cells(t, 1).Value = wshS.Cells(s, 1).Value c = 1 End If c = c + 1 wshT.Cells(t, c).Value = wshS.Cells(s, 2).Value Next s Application.ScreenUpdating = True End Sub(But PowerQuery might well be better)
Here is a macro you can run:
Sub Transform()
Dim wshS As Worksheet
Dim wshT As Worksheet
Dim s As Long
Dim m As Long
Dim t As Long
Dim c As Long
Application.ScreenUpdating = False
Set wshS = Worksheets("Current List")
Set wshT = Worksheets("Result")
wshT.Range("A2:A" & wshT.Rows.Count).EntireRow.Clear
m = wshS.Range("A" & wshS.Rows.Count).End(xlUp).Row
t = 1
For s = 2 To m
If wshS.Cells(s, 1).Value <> wshS.Cells(s - 1, 1).Value Then
t = t + 1
wshT.Cells(t, 1).Value = wshS.Cells(s, 1).Value
c = 1
End If
c = c + 1
wshT.Cells(t, c).Value = wshS.Cells(s, 2).Value
Next s
Application.ScreenUpdating = True
End Sub
HansVogelaar Thx for the macro, it works fine with the exception, that leading zeros in the values will be removed, e.g. 0000366 in the "Current List" is 366 in the "Result" table. I couldn't solve this with cell formatting, maybe it must be part of the macro?
- HansVogelaarMay 17, 2021MVP
Like this:
Sub Transform() Dim wshS As Worksheet Dim wshT As Worksheet Dim s As Long Dim m As Long Dim t As Long Dim c As Long Application.ScreenUpdating = False Set wshS = Worksheets("Current List") Set wshT = Worksheets("Result") wshT.Range("A2:A" & wshT.Rows.Count).EntireRow.Clear m = wshS.Range("A" & wshS.Rows.Count).End(xlUp).Row t = 1 For s = 2 To m If wshS.Cells(s, 1).Value <> wshS.Cells(s - 1, 1).Value Then t = t + 1 wshT.Cells(t, 1).EntireRow.NumberFormat = "@" wshT.Cells(t, 1).Value = wshS.Cells(s, 1).Value c = 1 End If c = c + 1 wshT.Cells(t, c).Value = wshS.Cells(s, 2).Value Next s Application.ScreenUpdating = True End Sub(But PowerQuery might well be better)
- Juergen_ThomaMay 25, 2021Copper Contributor
Hello together,
sorry for the late response. I just wanted to say that both solutions worked fine for me, thanks a lot for your feedback. In the end changing the query was the more efficient way, bacause I didn't have to load the entire table in Excel.
Best regards
Jürgen
- Riny_van_EekelenMay 17, 2021Platinum Contributor
Juergen_Thoma Why bother with VBA in the first place? You already use Power Query to connect to an SQL database with 799847 rows. Just add a few more applied steps and you're done. No need to load the entire table in an Excel either.