客户订单总计

时间:2017-06-04 00:53:47

标签: excel vba

我如何执行一个子程序,允许我根据他们的(客户ID)确定客户,以确定他们花了多少钱($ 3000)。同时查找每个客户在列表中花费的总金额,并将总数超过用户在新工作表上提供的金额(Ex $ 3000)报告到表单中,该表单生成每个客户花费的金额及其总金额在不同的牢房中向右边消费。

数据示例:

example data in excel

电流:

Sub test()

Sheets.Add after:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = "Report"


Lastrow = Sheets("Data").UsedRange.Rows.Count

Sheets("Data").Range("B3:B" & Lastrow).Copy

With Sheets("Report")
    .Range("A1").PasteSpecial Paste:=xlPasteValues
    .Activate
    .Range("B1").Select
    .Range(Range("A1"), Range("A1").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
    .Cells(1, 2).Value = "Subtotal"
End With

For i = 2 To ActiveSheet.UsedRange.Rows.Count
    Cells(i, 2).Value = Application.WorksheetFunction.SumIf(Sheets("Data").Range("B:B"), "=" & Cells(i, 1).Value, Sheets("Data").Range("C:C"))

Next

For i = ActiveSheet.UsedRange.Rows.Count To 2 Step -1
    If Cells(i, 2).Value < 3000 Then
        Cells(i, 2).EntireRow.Delete
    End If
Next

Sheets("Report").Range("A1:B" & ActiveSheet.UsedRange.Rows.Count).Sort KEY1:=Range("B1:B" & ActiveSheet.UsedRange.Rows.Count), Order1:=xlAscending, Header:=xlYes


End Sub

2 个答案:

答案 0 :(得分:1)

这可以在不使用VBA重新发明轮子的情况下完成。选择数据并插入数据透视表。这是基本的Excel功能,已经存在至少20年。

如果要使用VBA,请使用VBA创建数据透视表。

提示:在创建数据透视表之前,将源数据表转换为带有插入&gt;的Excel表对象。表(或Ctrl-T)。然后从Excel表创建一个数据透视表。这样,数据透视数据源将是动态的,当您向源添加更多数据时,您只需刷新数据透视表以包含新数据。

答案 1 :(得分:0)

以下将做到这一点。我没有使用动态范围来节省我输入更多,但这些都可以完成。

Sub CustomerSpending(cusID as Integer, overAmount as Double)

  'Point it at the correct worksheet where your data is.  Don't use Activesheet
  Dim ws as Worksheet
  Set ws = Thisworkbook.Worksheets("Your Worksheet Name")

  Dim TotalCustomerSpend as Double 'This is your final figure

  'Loop through every ID in the list of data
  For Each ID In ws.Range("Specify Your column and range here")
    'Check if the ID matches the one you are looking for
    If ID = cusID Then
      'Look at the column 1 accross from the ID (The spending amount)
      'Check if the spending amount is greater than the amount you specified
      If ID.Offset(0,1).Value > overAmount Then
        'If the amount is greater than what you specified then add it to the total
        TotalCustomerSpend = TotalCustomerSpend + ID.Offset(0,1).Value
      End If
    End If
  Next ID

然后您可以使用

调用sub
Call CustomerSpending(192,3000.00)

这将返回客户192超过3000美元的所有支出总和。对于所有支出,请执行以下操作

Call CustomerSpending(192,0)

将报告所有支出超过$ 0