试图完成sumifs(?)脚本

试图完成一个脚本,如果date是选定的月份,并且在适当的团队中,将会在C中添加值。 例:

| Team| Date| Cost| | 102|Mar-17| 13245| | 103|Jan-17| 2050| | 101|Feb-17| 1245| | 104|Jan-17| 12400| | 102|Mar-17| 5242| | 104|Jan-17| 600| | 102|Feb-17| 10240| | 102|Jan-17| 450| | 102|Mar-17| 12245| | 101|Jan-17| 2300| 

目的是让脚本确定我是否在寻找一月份:

  • 101 = 2300
  • 102 = 450
  • 103 = 2050
  • 104 = 13000

我一直在想这个,感觉卡住了。 在提供的公式中,cboMonth是从一个用户窗体和它的combobox确定为一个三个字母的月份。 cboYear是以类似的方式确定4位数。 最初的计划是使用一个循环,但我不知道如何把汇总function放在一起。 这是我迄今为止。

 Dim rng As Range Dim lastrow As Long Dim x As Integer Dim txt101 As Long Dim txt102 As Long Dim txt103 As Long Dim txt104 As Long Dim txt105 As Long lastrow = Cells(Rows.Count, "A").End(x1Up).Row ReportWbk.Sheets(cboYear).Activate Application.ScreenUpdating = False For Each x In Range("D" & lastrow) If x.Value = "FG-25" And x.Offset(, 1).Format(Month(mmm)) = cboMonth Then txt101 = txt102 = txt103 = txt104 = txt105 = End If Next x 

假设你的“团队”在列A中,“date”在列B中,“成本”在列C中,并且你的variablescboMonthcboYearStringtypes,你应该能够做到:

 'Convert input to a date Dim myDate As Date myDate = DateValue("1 " & cboMonth & " " & cboYear) 'Perform the required SUMIFS txt101 = Application.WorksheetFunction.SumIfs(Range("C:C"), _ Range("A:A"), "101", _ Range("B:B"), ">=" & myDate, _ Range("B:B"), "<=" & DateAdd("m", 1, myDate)) 'txt102 = 'txt103 = 'txt104 = 'txt105 = 

我不清楚你的数据是如何构build的,但是不应该太难以集成到你的代码中。