在循环内的循环中使用计数器= excel vba中的问题

时间:2017-06-16 00:17:56

标签: excel vba loops counter

嗨,谢谢你的帮助。

我是excel的总菜鸟,但由于我的研究需要,我一直在教自己 我通过从youtube频道ExcelVbaIsFun

调整它来创建这个基本代码
Sub ZipCodeSum2()

Dim dbsheet As Worksheet
Set dbsheet = ThisWorkbook.Sheets("Sheet1")
lr = dbsheet.Cells(Rows.Count, 1).End(xlUp).Row
SelRow = Selection.Row
'zip code
zip = dbsheet.Cells(SelRow, 2)

For i = 2 To lr 'change lr to 3 for testing purposes
Cells(i, 3).Select

 For x = 2 To lr 'change lr to 10 for testing purposes
    If dbsheet.Cells(x, 2) = zip Then
        counter = counter + dbsheet.Cells(x, 1)
    ActiveCell = counter
    End If

 Next x

Next i

End Sub

问题在于,对于第一个'i'“外循环”运行正常并且sum函数运行良好。但是,在下一个'i'中它会添加第一个'i'总和的结果,然后再添加第二个'i'总和。因此,如果邮政编码是相同的,它基本上导致第二个'i'是我想要的结果的两倍。

任何帮助将不胜感激!谢谢!

sample of my worksheet

2 个答案:

答案 0 :(得分:1)

在C2试试,

=sumifs(a$2:a2, b$2:b2, b2)

根据需要填写。

如果您只希望值的最后一个实例显示总和,那么

=IF(COUNTIF(A$2:A2, A2)=COUNTIF(A:A, A2), SUMIFS(A$2:A2, B$2:B2, B2), TEXT(,))

答案 1 :(得分:1)

如果您希望在执行内循环之前重置counter,请在进入该循环之前将其初始化:

Sub ZipCodeSum2()
    Dim dbsheet As Worksheet
    Dim lr As Long
    Dim SelRow As Long
    Dim zip As String
    Dim i As Long
    Dim counter As Currency
    Dim x As Long

    Set dbsheet = ThisWorkbook.Sheets("Sheet1")
    lr = dbsheet.Cells(dbsheet.Rows.Count, 1).End(xlUp).Row

    For i = 2 To lr 'change lr to 3 for testing purposes
        'zip should be set inside the "For i" loop
        zip = dbsheet.Cells(i, "B").Value
        counter = 0
        For x = 2 To lr 'change lr to 10 for testing purposes
            If dbsheet.Cells(x, "B").Value = zip Then
                counter = counter + dbsheet.Cells(x, "A").Value
            End If
        Next 
        dbsheet.Cells(i, "C").Value = counter
    Next i
End Sub

但这可以简化为:

Sub ZipCodeSum2()
    With ThisWorkbook.Sheets("Sheet1")
        With .Range("C2:C" & .Cells(.Rows.Count, "A").End(xlUp).Row)
            .Formula = "=SUMIF(B:B,B2,A:A)"
            .Value = .Value
        End With
    End With
End Sub

或者你可以放置公式

=SUMIF(B:B,B2,A:A)

进入Excel中的单元格C2并将其复制下来。