Sub FilterByMaterialCreateSheet_v02()
Dim shtSrc As Worksheet, shtDest As Worksheet
Dim rngSrc As Range, arrSrc As Variant
Dim lrowSrc As Long, lcolSrc As Long, colSrcFltr As Long
Dim dictMaterial As Object, dictKey As String, vKey As Variant
Dim i As Long
Dim sName As String
Dim illegalNmChar As Variant
Dim replaceNmChr As String
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
illegalNmChar = Array("/", "\", "[", "]", "*", "?", ":")
replaceNmChr = "|"
Set shtSrc = Worksheets("Data") ' <--- Change to your sheet name
With shtSrc
lrowSrc = .Cells(Rows.Count, "I").End(xlUp).Row
lcolSrc = .Cells(6, Columns.Count).End(xlToLeft).Column
Set rngSrc = .Range(.Cells(6, "A"), .Cells(lrowSrc, lcolSrc))
arrSrc = rngSrc
colSrcFltr = .Columns("I").Column - rngSrc.Cells(1).Column + 1 ' <--- Column letter to use for filtering
End With
Set dictMaterial = CreateObject("Scripting.dictionary")
' Load unique materials into Dictionary
For i = 2 To UBound(arrSrc)
dictKey = arrSrc(i, colSrcFltr)
If Not dictMaterial.exists(dictKey) And dictKey <> "" Then
dictMaterial(dictKey) = i
End If
Next i
If shtSrc.AutoFilterMode Then shtSrc.AutoFilterMode = False
For Each vKey In dictMaterial.keys
rngSrc.AutoFilter Field:=colSrcFltr, Criteria1:=vKey
If rngSrc.SpecialCells(xlCellTypeVisible).Count > 1 Then
Set shtDest = Worksheets.Add(After:=Sheets(Sheets.Count))
On Error Resume Next
shtDest.Name = vKey
If Err <> 0 Then
If InStr(1, Err.Description, "taken", vbTextCompare) > 0 Then
Application.DisplayAlerts = False
Worksheets(vKey).Delete
Application.DisplayAlerts = True
shtDest.Name = vKey
ElseIf Len(vKey) > 31 Then
shtDest.Name = Left(vKey, 31)
Else
sName = vKey
For i = 0 To UBound(illegalNmChar)
sName = Replace(sName, illegalNmChar(i), replaceNmChr)
Next i
shtDest.Name = sName
End If
End If
On Error GoTo 0
' Copy in heading rows and resize column widths
shtSrc.Rows("1:5").Copy
shtDest.Rows("1:5").PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
shtDest.Rows("1:5").PasteSpecial Paste:=xlPasteAll
' Copy filtered data
rngSrc.Copy Destination:=shtDest.Range("A6")
shtDest.Activate
shtDest.Range("A1").Select
End If
Next vKey
shtSrc.ShowAllData
shtSrc.Activate
shtSrc.Range("A1").Select
Application.CutCopyMode = False
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub