簡體   English   中英

Excel VBA循環使用條件和2張紙

[英]Excel VBA Looping using criteria and 2 sheets

我正在嘗試做一些我確實不確定該怎么做的事情。

我有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多行要遍歷5張紙。

這是一個完成所需工作的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM