VBA Sumifs MultiSelect Item ListboxList

VBA Sumifs MultiSelect Item ListboxList

我有一个 MultiSelect 列表框,其中填充了周值 (1,2,3...52),我可以在其中 select 多个星期。我想要的是制作一个 Sumifs 以根据 selected.

项目获取访问过的零售商的数量

例如:如果我 select 第 27 周和第 28 周,我想要第 27 周和第 28 周访问过的零售商数量的总和。

目前,即使我 select 多个项目,我也只有一周的结果。

Sub SumifsVisitedRetailer()

  Dim StartRow As Long
  Dim LastRow As Long
  Dim FoundColumn As String
  Dim StringToFind As String
  Dim ResultRange As Range
  Dim i as Integer, Dim x as Integer 
  Dim Measure as range, Dim retailer as range

  Dim bdd As Worksheet: Set bdd = Sheets("BDD")
  Dim cht As Worksheet: Set cht = Sheets("CHT")

  Call FoundMeasure(StartRow, LastRow, FoundColumn, StringToFind, ResultRange, Measure)
  Call FoundColRetailer(StartRow, LastRow, FoundColumn, StringToFind, ResultRange, retailer)

    LastRange = .Cells(Rows.Count, 1).End(xlUp).Row

    'Column Week
    Set wkcol = bdd.Range("D2:D" & LastRange)

      LastRow = cht.Cells(Rows.Count, 1).End(xlUp).Row

            For x = 0 To UserForm1.ListBox32.ListCount - 1

             For I = 2 To LastRow

               If UserForm1.ListBox32.Selected(x) = True Then

                 cht.Cells(I, 2) = Application.WorksheetFunction.SumIfs(Measure, retailer, 
                   cht.Cells(I, 1), wkcol, UserForm1.ListBox32.List(x)) 
               End If
            Next I
           Next x

End Sub

您可以在将每个 SumIfs 公式的结果添加到目标单元格之前清除单元格的值。像这样的东西应该有用...

' Range to add SumIfs in
Dim target as Range
Set target = cht.Cells(I, 2) ' Or something, I'm not quite following your data :)
' Clear the target range's value
target.value = 0
' For each week to calculate SumIfs with
For x = 0 To UserForm1.ListBox32.ListCount - 1
     ' Add the value of the cell to the result of the SumIf function
     target.value = target.value + Application.WorksheetFunction.SumIfs( _
                                                 Measure, _
                                                 retailer, _
                                                 cht.Cells(I, 1), _
                                                 wkcol, _
                                                 UserForm1.ListBox32.List(x))
Next x