sumifs函数的VBA代码

时间:2014-05-12 07:38:51

标签: vba excel-vba excel

我有以下代码,我得到运行时错误' 1004'它是以文本作为变量吗?香港专业教育学院也试过直接引用包含我的条件的单元格,但有同样的问题

Sub sumifs()
Dim Month_tally As Double
Dim Monthrange As Range

Set Monthrange = Range("B2:D5")
Set months = Range("B1:D1")
Set Prospects = Range("A2:A4")

Range("B6").Formula = WorksheetFunction.sumifs(Monthrange, months, (May), Prospects, (CN))

End Sub


May June    July
CN 456 2 2 Nj 2 2 2 BH 2 456 5647 BG 4567 2 2

2 个答案:

答案 0 :(得分:0)

用户定义的函数可能以's'结尾,但Excel工作表函数只是'sumif',只需3个参数:range,criteria,sum_range。也许你真的想要这样做:

Range("B6").FormulaR1C1 = "=SUM(  OFFSET( R[-4]C[-1], 0, MATCH(""May"", R[-5]C:R[-5]C[2], FALSE), 4, 1 )  )"

修改

好的,试试这个:

Sub sumifs()
    'Dim Month_tally As Double
    Dim Monthrange As Range
    Dim Months As Range
    Dim CriteriaRange As Range
    Set Monthrange = Range("A1:D5")   'Include the first column and header row
    Set Months = Range("B1:D1")
    Set CriteriaRange = Range("A10:A11")
    'Set Prospects = Range("A2:A4")

    Range("A1").Value = "Prospects"   ' just to ensure first column has header

    Range("A10").Value = "Prospects"
    Range("A11").Value = "CN"
    Range("B10").Value = "Column to sum"
    Range("B11").Value = "May"

    Range("B6").Value = WorksheetFunction.DSum(Monthrange, Range("B11"), CriteriaRange)

End Sub

当然,通过数据透视表变得微不足道。您能否将源数据结构化为3列:Prospects,Month,ProdQ​​ty?

答案 1 :(得分:0)

只需删除" s"在WorksheetFunction.sumifs结束时使用正确的语法。