【问题标题】:Excel VBA Looping using criteria and 2 sheetsExcel VBA循环使用标准和2张
【发布时间】:2012-07-02 20:25:32
【问题描述】:

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

我有 2 个电子表格 sheet1 和 sheet2

在第一张我有
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 函数在一个单元格中执行此操作,但我总共有 5 张纸要处理超过 500 行。

【问题讨论】:

  • 认为我已经正确解释了描述以显示示例数据。 @user1497083 如果有问题,请再次编辑问题。
  • 似乎是数据透视表的好用例
  • 您正在寻找 Excel 中的 数据透视表 功能。

标签: excel vba loops


【解决方案1】:

这是一个执行所需工作的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多