Option Explicit
Sub ProcessResults()
Dim wsData As Worksheet
Dim rAnchorCellData As Range
Dim rAnchorCellResults As Range
Dim rCell As Range
Dim sFileNameLabel As String
Dim sFileName As String
Dim sDataLabel As String
Dim sResultsLabel As String
Dim sItemName As String
Dim iItemNextQuantity As Long
Dim iItemExistingQuantity As Long
Dim iResultsRowsCount As Long
Dim iDataRow As Long
Dim vKey As Variant
Dim dicData As Object
Set dicData = CreateObject("Scripting.Dictionary")
sFileNameLabel = "File Name"
sDataLabel = "Data"
sResultsLabel = "Results"
Set wsData = ActiveSheet
Set rCell = FindCell(wsData, sFileNameLabel)
If rCell Is Nothing _
Then
MsgBox "Could not find the label cell for the file name (" & sFileNameLabel & ").", vbInformation
Exit Sub
Else
sFileName = rCell.Offset(0, 1).Value
End If
Set rAnchorCellData = FindCell(wsData, sDataLabel)
If rAnchorCellData Is Nothing _
Then
MsgBox "Could not find the label cell for data (" & sDataLabel & ").", vbInformation
Exit Sub
End If
Set rAnchorCellData = rAnchorCellData.Cells.Offset(2)
Set rAnchorCellResults = FindCell(wsData, sResultsLabel)
If rAnchorCellResults Is Nothing _
Then
MsgBox "Could not find the label cell for results (" & sResultsLabel & ").", vbInformation
Exit Sub
End If
Set rAnchorCellResults = rAnchorCellResults.Cells.Offset(2)
iResultsRowsCount = rAnchorCellResults.CurrentRegion.Rows.Count - 1
If iResultsRowsCount <> 0 _
Then rAnchorCellResults.Offset(1).Resize(iResultsRowsCount, 2).Clear
With rAnchorCellData
iDataRow = 0
Do
sItemName = .Offset(iDataRow + 1, 0).Value
iItemNextQuantity = .Offset(iDataRow + 1, 1).Value
If Not dicData.Exists(sItemName) _
Then
dicData.Add sItemName, iItemNextQuantity
Else
iItemExistingQuantity = dicData(sItemName)
iItemNextQuantity = iItemNextQuantity + iItemExistingQuantity
dicData(sItemName) = iItemNextQuantity
End If
iDataRow = iDataRow + 1
Loop Until .Offset(iDataRow + 1) = ""
End With
iDataRow = 0
With rAnchorCellResults
For Each vKey In dicData.Keys
iDataRow = iDataRow + 1
With .Offset(iDataRow, 0)
.Value = vKey
End With
With .Offset(iDataRow, 1)
.Value = dicData(vKey)
End With
Next vKey
End With
Call ExportRangeToCSVFile(rAnchorCellResults.CurrentRegion, sFileName)
End Sub