Here is a start for 10. I will add more commentary after meeting.
Note: Does require .Net framework.
Option Explicit
Public Sub FruitItems()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("fruitData")
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim fruitDataArray()
fruitDataArray = ws.Range("A1:C" & lastRow)
Dim fruitSortedList As Object
Set fruitSortedList = CreateObject("System.Collections.Sortedlist")
Dim currentFruit As Long
On Error Resume Next
For currentFruit = LBound(fruitDataArray, 1) + 1 To UBound(fruitDataArray, 1)
fruitSortedList.Add fruitDataArray(currentFruit, 1), fruitDataArray(currentFruit, 1)
Next currentFruit
On Error GoTo 0
Dim i As Long
For i = 0 To fruitSortedList.Count - 1
'Debug.Print fruitSortedList.GetKey(i) & vbTab & fruitSortedList.GetByIndex(i)
For currentFruit = LBound(fruitDataArray, 1) + 1 To UBound(fruitDataArray, 1)
If fruitDataArray(currentFruit, 1) = fruitSortedList.GetKey(i) Then 'sorted order
Dim newSheet As Worksheet
Dim fruitName As String
fruitName = fruitDataArray(currentFruit, 1)
If SheetExists(fruitName) Then
Set newSheet = wb.Worksheets(fruitName)
Else
Set newSheet = wb.Worksheets.Add(After:=wb.Worksheets(Worksheets.Count))
newSheet.Name = fruitName
End If
Dim counter As Long
counter = GetLast(newSheet, True) + 1
With newSheet
.Cells(counter, 1) = fruitDataArray(currentFruit, 1)
.Cells(counter, 2) = fruitDataArray(currentFruit, 2)
.Cells(counter, 3) = fruitDataArray(currentFruit, 3)
counter = counter + 1
End With
Set newSheet = Nothing
End If
Next currentFruit
Next i
End Sub
'@TimWilliams
Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
'@Raystafarian
Private Function GetLast(ByVal targetSheet As Worksheet, ByVal isRow As Boolean) As Long
If isRow Then
GetLast = targetSheet.Cells(Rows.Count, 1).End(xlUp).Row
Else
GetLast = targetSheet.Cells(1, Columns.Count).End(xlToLeft).Column
End If
End Function
References:
- https://codereview.stackexchange.com/questions/187246/reorder-columns-in-array
- https://msdn.microsoft.com/en-us/library/system.collections.sortedlist(v=vs.110).aspx
- http://www.robvanderwoude.com/vbstech_data_sortedlist.php
- Adding sheets to end of workbook in Excel (normal method not working?)
- Test or check if sheet exists