2017-06-04 105 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表中創建一個數據透視表。這樣,數據透視表數據源將是動態的,當您向數據源添加更多數據時,只需刷新數據透視表以包含新數據即可。