It was an issue if the second to last sales order only had one item:
Sub TestMacro()
Dim rngC As Range
Dim rngA As Range
Dim rngL As Range
Dim i As Integer
Dim c As Integer
Dim j As Integer
Dim rngS As Range
Dim rAnchor As Range
Set rAnchor = Application.InputBox("Pick the cell with the first sales order number", Type:=8)
Set rngL = Range(rAnchor, Cells(Rows.Count, rAnchor.Column + 1).End(xlUp)(1, 0))
Set rngS = rngL.SpecialCells(xlCellTypeConstants)
c = rngS.Areas.Count
Set rngA = rngS.Areas(c)
If rngA.Cells.Count > 1 Then
MakeList Range(rngA.Cells(rngA.Cells.Count), rngL.Cells(rngL.Cells.Count))
For j = rngA.Cells.Count - 1 To 1 Step -1
MakeList rngA.Cells(j)
Next j
Else
MakeList Range(rngA, rngL.Cells(rngL.Cells.Count))
End If
For i = c - 1 To 1 Step -1
Set rngA = rngS.Areas(i)
Set rngA = Range(rngA.Cells(rngA.Cells.Count), rngS.Areas(i + 1).Cells(0))
MakeList rngA
If rngS.Areas(i).Cells.Count > 1 Then
For j = 1 To rngS.Areas(i).Cells.Count - 1
MakeList rngS.Areas(i).Cells(j)
Next j
End If
Next i
rAnchor.Resize(1, 2).EntireColumn.AutoFit
rAnchor.Offset(0, 2).EntireColumn.Delete
End Sub
Sub MakeList(r As Range)
Dim c As Range
Dim strV As String
For Each c In r.Offset(0, 1)
If Application.CountIf(Range(r.Cells(1), c), c) = 1 Then
strV = strV & IIf(strV <> "", ", ", "") & _
Application.SumIf(r.Offset(0, 1), c, r.Offset(0, 2)) & "-" & c.Value
End If
Next c
r.Cells(1).Offset(0, 1).Value = strV
If r.Cells.Count > 1 Then
r.Cells(2).Resize(r.Cells.Count - 1, 3).Delete xlUp
End If
r.Cells(1, 3).ClearContents
End Sub
-
Marked as answer by
A_Shannon828
Friday, May 22, 2015 8:43 PM