Sub Unique_Values_Sumif()
Application.DisplayAlerts = False
Dim tb As Worksheet
Dim tb2 As Worksheet
Dim actvSheet As String
actvSheet = ActiveSheet.Name
Set tb = Sheets(actvSheet)
Dim rSelection As Range, lColNo As Integer, formulalColNo As Integer, fColNo As Integer, formulafColNo As Integer
'Check that a range is selected
If Selection.Columns.Count < 2 Then
MsgBox "Please select a range first, you have slected only 1 column, column must be at least 2", vbOKOnly, "Selecton Check"
Exit Sub
End If
'Store the selected range
Set rSelection = Selection
fColNo = rSelection.Column
formulafColNo = fColNo - 2
lColNo = rSelection(rSelection.Count).Column
formulalColNo = lColNo - 2
Dim VLformulafColNo As Integer, VLformulalColNo As Integer, VLlookupColNo As Integer
VLformulafColNo = fColNo - 3
VLformulalColNo = lColNo - 3
VLlookupColNo = Selection.Columns.Count
Set tb2 = Worksheets.Add(Type:=xlWorksheet, after:=Application.ActiveSheet)
rSelection.Copy tb2.Range("A3")
On Error Resume Next
With tb2
.Range("A3:A5000").SpecialCells(xlCellTypeBlanks).Delete shift:=xlShiftUp
.Range("B1:Z5000").ClearContents
.Range("A3").CurrentRegion.RemoveDuplicates 1
With .Range(.Range("B3"), .Range("A3").End(xlDown).Offset(, 1))
.FormulaR1C1 = "=SUMIF('" & actvSheet & "'!C[" & formulafColNo & "]:C[" & formulafColNo & "],RC[-1],'" & actvSheet & "'!C[" & formulalColNo & "]:C[" & formulalColNo & "])"
End With
'Autofit column
.Columns("A").AutoFit
.Range("B1").Formula = "=SUM(B3:B5000)"
.Range("A1").Formula = "=COUNTA(A3:A5000)"
.Range("A2").Value = "ART"
.Range("B2").Value = "QTY"
.Range("C2").Value = "VLOOKUP"
.Range("D2").Value = "COUNT"
With .Range(.Range("c3"), .Range("b3").End(xlDown).Offset(, 1))
.FormulaR1C1 = "=VLOOKUP(RC[-2],'" & actvSheet & "'!C[" & VLformulafColNo & "]:C[" & VLformulalColNo & "]," & VLlookupColNo & "," & 0 & ")"
End With
With .Range(.Range("D3"), .Range("C3").End(xlDown).Offset(, 1))
'------
.FormulaR1C1 = "=COUNTIF('" & actvSheet & "'!C[" & formulafColNo - 2 & "]:C[" & formulafColNo - 2 & "],RC[-3])"
End With
End With
Application.DisplayAlerts = True
Done:
Exit Sub
End Sub