2017-06-04 135 views
-2

我该如何执行一个子分类,以便根据他们的(客户ID)确定客户来确定他们在总共花费了多少($ 3000)时所花费的金额。除了查找每个客户在列表中花费的总金额并将其总数超过用户在新工作表中提供的金额(例如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 
+3

那么你尝试过什么到目前为止,所有的开支? – avojak

+0

我目前有清单显示客户ID和总金额,但他们似乎在重复。以及我需要更改量变量,使用主工作表上的按钮进行更改。 – JaySmith

回答

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 

你可以调用子与

Call CustomerSpending(192,3000.00) 

这将返回所有花费为客户192的总和超过$ 3000对于所有的支出做以下

Call CustomerSpending(192,0) 

这将报告192超过$ 0

1

这可以在不重新发明与VBA车轮来完成。选择数据并插入数据透视表。这是基本的Excel功能,至少已经存在了20年。

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

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