Excel VBA循环使用标准和2张

时间:2012-07-02 20:25:32

标签: excel vba loops

我正在尝试做一些我真的不确定该怎么做的事情。

我有2张电子表格sheet1和sheet2

在表1中我有 A列数字列表(SalespersonsID)
B列是表2中B列的总和

SalespersonID | Total sales
--------------+------------
            1 | 
            2 |  
表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行要完成。

1 个答案:

答案 0 :(得分: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