VBA:带for for循环的sum变量

时间:2017-12-17 22:26:18

标签: excel vba loops sumifs

我正在尝试对行中包含特定文本字符串的单元格求和。下面是我提出的,但是,当它到达第一个货币文本时,我在第二个循环上一直收到错误。

  

运行时错误'6':溢出

    'Add Futures Data
        Morgan_Stanley_File.Activate
        Dim Currency_JPY As Integer: Currency_JPY = 0
        Dim Currency_USD As Integer: Currency_USD = 0
        Dim Currency_EUR As Integer: Currency_EUR = 0
        Dim Currency_GBP As Integer: Currency_GBP = 0
        Dim Currency_AUD As Integer: Currency_AUD = 0

        For Each MCell In Range("H1:H" & bottomL)
            If MCell.Value = "N" And MCell.Offset(0, -3) = "JPY" Then
                Currency_JPY = Currency_JPY + MCell.Offset(0, 19).Value
            ElseIf MCell.Value = "N" And MCell.Offset(0, -3) = "USD" Then
                Currency_USD = Currency_USD + MCell.Offset(0, 19).Value
            ElseIf MCell.Value = "N" And MCell.Offset(0, -3) = "EUR" Then
                Currency_EUR = Currency_EUR + MCell.Offset(0, 19).Value
            ElseIf MCell.Value = "N" And MCell.Offset(0, -3) = "GBP" Then
                Currency_GBP = Currency_GBP + MCell.Offset(0, 19).Value
            ElseIf MCell.Value = "N" And MCell.Offset(0, -3) = "AUD" Then
                Currency_AUD = Currency_AUD + MCell.Offset(0, 19).Value
            End If
        Next MCell

        wb.Activate
        Initial_Margin.Select
        Range("A" & LastDate).Offset(1, 5).Value = Currency_JPY
        Range("A" & LastDate).Offset(1, 6).Value = Currency_USD
        Range("A" & LastDate).Offset(1, 7).Value = Currency_EUR
        Range("A" & LastDate).Offset(1, 8).Value = Currency_GBP
        Range("A" & LastDate).Offset(1, 9).Value = Currency_AUD

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

考虑Excel的公式函数SUMIFS(),它允许多个条件,类似于AVERAGEIFS()。对于中位数,最大值,最小值等其他聚合,单元格中有array formula。无需VBA for循环或if逻辑。

A       B       C
N     150     USD
N     250     JPY
N     175     EUR
Y     185     JPY
N     225     USD
N     225     AUD
N     225     GPD
...

[JPY TOTAL CELL] = SUMIFS($B$1:$B$100, $C$1:$C$100, "JPY", $A$1:$A$100, "N")
[USD TOTAL CELL] = SUMIFS($B$1:$B$100, $C$1:$C$100, "USD", $A$1:$A$100, "N")
[EUR TOTAL CELL] = SUMIFS($B$1:$B$100, $C$1:$C$100, "EUR", $A$1:$A$100, "N")
[GBP TOTAL CELL] = SUMIFS($B$1:$B$100, $C$1:$C$100, "GBP", $A$1:$A$100, "N")
[AUD TOTAL CELL] = SUMIFS($B$1:$B$100, $C$1:$C$100, "AUD", $A$1:$A$100, "N")