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

Using a counter in a loop within a loop = problems in excel vba

您好,感谢您的帮助。

我完全是 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' "outer loop" 运行良好并且求和函数运行良好。但是,在接下来的 'i' 中,它添加了第一个 'i' 和的结果,然后也将第二个 'i' 和的结果添加到它。因此,如果邮政编码相同,则基本上会导致第二个 'i' 是我想要的结果的两倍。

如有任何帮助,我们将不胜感激!谢谢!

sample of my worksheet

在C2尝试,

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

按要求填写。

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

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

如果你想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并复制下来。