2012-07-02 18 views
0

我正在嘗試做一些我真的不知道該怎麼做的事情。Excel VBA循環使用標準和2張

我有2個擴展片爲sheet1和sheet2

在片1 I有
列A編號(SalespersonsID)
B欄柱B的總和上薄片的列表2

SalespersonID | Total sales 
--------------+------------ 
      1 | 
      2 | 

on sheet 2我有
A列有salespersonsID
列B有銷售人員在該交易中銷售了多少小部件
塔C TypeofWidget
列d具有位置

SalespersonID | Units sold | Type | Location 
--------------+------------+------+----------- 
      1 |   1 | Foo | London 
      1 |   2 | Bar | London 
      2 |   4 | Foo | Berlin 
      1 |   1 | Bar | Madrid 

我不知道如何做到這一點,但我需要使用Sheet2中的列C和d,也表插入總額一個推銷員銷售的小部件的數量1的銷售ID作爲條件並將其插入Sheet1列B?

SalespersonID | Total sales 
--------------+------------ 
      1 |   4 
      2 |   4 

我能做到這一點在使用SUMIFS函數的單元格,但我有超過500行至第5張共經歷。

+0

I * *認爲我正確地解釋說明,以顯示樣本數據。 @ user1497083如果有問題,請再次編輯問題。 –

+0

似乎是數據透視表的良好用例 –

+0

您正在尋找Excel中的*數據透視表*功能。 –

回答

0

這是一個VBA子是做必要的工作,只是把它放在VBA和運行:

sub totalSales() 
    Dim i As Integer 'used to loop on sheet1 
    Dim j As Integer 'used to loop on sheet2 
    Dim spID As Integer 'the SalepersonID in Sheets1 
    Dim spID2 As Integer 'the SalepersonID in Sheets2 
    Dim rows1 as Integer 'rows count in sheet1 
    Dim rows2 as Integer 'rows count in sheet2 
    Dim total as Integer 'to count sales per person 

    'getting rows count 
    rows1=Worksheets("sheet1").Cells(Rows.Count, "A").End(xlUp).Row 'rows count in sheet1 
    rows2=Worksheets("sheet2").Cells(Rows.Count, "A").End(xlUp).Row 'rows count in sheet2 

    For i = 1 To rows1 
     spID = Worksheets("sheet1").Cells(i, "A").Value) 'the salepersonID 
     total=0 'initializing counter 
     for j= 1 to rows2 
      spID2 = Worksheets("sheet2").Cells(j, "A").Value 
      If (UserID=UserID2) Then 
       total = total + Worksheets("sheet2").Cells(j, "B").Value 
      End If 
     next j 
     Worksheets("sheet2").Cells(i, "B").Value = total ' Storing the total in sheet1 
    next i 

End Sub