See attached file where I added this macro:
Sub macro1()
Dim refSh As Worksheet
Dim resSh As Worksheet
Dim refLr As Long, resLr As LoadPictureConstants
Dim resLc As Integer, r As Long
Dim newSh As Worksheet, sh As Variant
Dim fruitName As String, foundRows As Long
Application.ScreenUpdating = False
With ThisWorkbook
Set refSh = .Sheets("reference")
Set resSh = .Sheets("results")
'remove filter from result sheet
resSh.AutoFilterMode = False
resLr = resSh.Cells(Rows.Count, "t").End(xlUp).Row
resLc = resSh.Cells(1, Columns.Count).End(xlToLeft).Column
'delete all sheets
For Each sh In ThisWorkbook.Sheets
Application.DisplayAlerts = False
If sh.Name <> refSh.Name And sh.Name <> resSh.Name Then
sh.Delete
End If
Application.DisplayAlerts = True
Next
'for each fruit
resSh.Activate
refLr = refSh.Cells(Rows.Count, 1).End(xlUp).Row
For r = 2 To refLr
fruitName = refSh.Cells(r, 2)
resSh.Range("t:t").AutoFilter Field:=1, Criteria1:="=*" & fruitName & "*"
foundRows = 0
'get rows found
On Error Resume Next
foundRows = resSh.Range("t2:t" & resLr).SpecialCells(xlCellTypeVisible).Cells.Count
On Error GoTo 0
Set newSh = .Sheets.Add(, .Sheets(.Sheets.Count))
If foundRows > 0 Then
refSh.Cells(r, "c") = foundRows
newSh.Name = fruitName & " (" & foundRows & ")"
resSh.Cells(1, 1).Resize(resLr, resLc).Copy newSh.Cells(1, 1)
Else
newSh.Name = fruitName
End If
Next r
End With
resSh.AutoFilterMode = False
refSh.Activate
Application.ScreenUpdating = True
End Sub
Regards,
Antonio
Bookmarks