how do I sum data in a given colum for a dynamic range which is based on customer ID. The example with test data is attached. I asked this question in another thread but sadly i did not follow the forum rules hece this new thread. In the attahed file I have a list of customer transactions which shows sales units and sales value.
A customer can have 1:N rows. I would like to add all sales units and sales value for a given customer and perform a check on the results. ie if sum of all sales units = 0 and sum of all sales value then returm "Exchange". The problem is that i am only able to compare two rows at a time but I would like to sum on the range of customer ID's. The range is dynamic. My code is as follows: As I say it works but not the way I would like it, you should be able to run the code with the attached file
[*
- Code: Select all
Dim i As Long
Dim RwCount As Long
Dim Customer_ID As Range
Dim sales_unit_ID As Range
Dim sales_value_ID
Dim CustomerID1 As String 'Customer ID value
Dim CustomerID2 As String 'Customer ID value
Dim Result As Range 'Output string - actual result
Dim Sales_Value1 As Double 'sales value
Dim Sales_Value2 As Double 'Sales value
Dim Sales_Unit1 As Double 'Sales Unit value
Dim Sales_Unit2 As Double 'Sales unit Value
Dim Total_Sales As Double
Dim total_units As Double
Set dict = CreateObject("scripting.dictionary")
'Count Cells using the Customer ID
RwCount = Cells(Cells.Rows.Count, "A").End(xlUp).Row
For i = RwCount To 2 Step -1
'Set columns to be evaluated
Set Customer_ID = Cells(i, "A") 'Customer ID column
Set sales_unit_ID = Cells(i, "B") 'Sales unit column
Set sales_value_ID = Cells(i, "C") 'Sales value column
Set Result = Cells(i, "D")
'Capture data from the define columns
CustomerID1 = Customer_ID.Offset(0, 0)
CustomerID2 = Customer_ID.Offset(-1, 0)
Sales_Unit1 = sales_unit_ID
Sales_Unit2 = sales_unit_ID.Offset(-1, 0)
Sales_Value1 = sales_value_ID
Sales_Value2 = sales_value_ID.Offset(-1, 0)
If ((Customer_ID.Offset(0, 0) = Customer_ID.Offset(-1, 0)) And ((Sales_Value1 = 0 Or Sales_Value2 = 0 Or Sales_Value1 < 0 Or Sales_Value2 < 0) And (Sales_Unit1 = 0 Or Sales_Unit2 = 0))) Then
Result.Offset(0, 0) = "Exchange"
Result.Offset(-1, 0) = "Exchange"
ElseIf ((CustomerID1 = CustomerID2) And ((Sales_Value1 < 0 Or Sales_Value2 < 0) And (Sales_Unit1 < 0 Or Sales_Unit2 < 0))) Then
Result.Offset(0, 0) = "Refund"
Result.Offset(-1, 0) = "Refund"
Else
Result.Offset(-1, 0) = "--OK--"
If Customer_ID.Value = "Exchange/refund" Then Exit Sub
End If
Next i
End Sub