Well, if you delete that value, my previous code should work... but to avoid errors, I can just ignore "D" if "C" has a value:
Sub fruit()
Dim ws As Worksheet
Dim lr As Long
Dim i As Long
Dim myDictionary As Object
Application.ScreenUpdating = False
Set ws = Worksheets("Sheet1")
lr = ws.Range("A" & Rows.Count).End(xlUp).Row
Set myDictionary = CreateObject("Scripting.Dictionary")
For i = lr To 2 Step -1
If Not myDictionary.Exists(ws.Range("A" & i).Value) Then
myDictionary.Add ws.Range("A" & i).Value, -1 * ws.Range("C" & i).Value
Else
myDictionary(ws.Range("A" & i).Value) = myDictionary(ws.Range("A" & i).Value) + IIf(ws.Range("C" & i).Value = vbNullString, ws.Range("D" & i).Value, -1 * ws.Range("C" & i).Value)
End If
If ws.Range("C" & i).Value = vbNullString Then
ws.Range("E" & i).Value = myDictionary(ws.Range("A" & i).Value)
If myDictionary(ws.Range("A" & i).Value) < 0 Then
ws.Range("E" & i).Font.Color = vbRed
Else
ws.Range("E" & i).Font.Color = vbGreen
End If
Else
ws.Range("E" & i).Font.Color = vbBlack
End If
Next i
Application.ScreenUpdating = True
End Sub
The code DOES assume that the first instance (when working from the bottom to the top) of any fruit will have a buying price.
Bookmarks