Sum Column B based on Column A using Excel VBA Macro

后端 未结 6 708
清酒与你
清酒与你 2021-01-17 00:59

OK, I have a simple problem that I need help with in a VBA Macro. I have an excel sheet that looks like this...

Product #     Count
101              1
102          


        
6条回答
  •  猫巷女王i
    2021-01-17 01:49

    Assuming the data is in columns A and B, you can do it with a formula:

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

    Or if you put 101 in C1:

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

    EDIT

    However if you still require VBA, here is my (quick and dirty) proposal - I use a dictionary to keep track of the sum for each item.

    Sub doIt()
    
      Dim data As Variant
      Dim i As Long
      Dim countDict As Variant
      Dim category As Variant
      Dim value As Variant
    
      Set countDict = CreateObject("Scripting.Dictionary")
    
      data = ActiveSheet.UsedRange 'Assumes data is in columns A/B
    
      'Populate the dictionary: key = category / Item = count
      For i = LBound(data, 1) To UBound(data, 1)
        category = data(i, 1)
        value = data(i, 2)
        If countDict.exists(category) Then
          countDict(category) = countDict(category) + value 'if we have already seen that category, add to the total
        Else
          countDict(category) = value 'first time we find that category, create it
        End If
      Next i
    
      'Copy dictionary into an array
      ReDim data(1 To countDict.Count, 1 To 2) As Variant
    
      Dim d As Variant
      i = 1
      For Each d In countDict
        data(i, 1) = d
        data(i, 2) = countDict(d)
        i = i + 1
      Next d
    
      'Puts the result back in the sheet in column D/E, including headers
      With ActiveSheet
        .Range("D1").Resize(UBound(data, 1), UBound(data, 2)) = data
      End With
    
    End Sub
    

提交回复
热议问题