Sum Column B based on Column A using Excel VBA Macro

后端 未结 6 710
清酒与你
清酒与你 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条回答
  •  梦谈多话
    2021-01-17 01:51

    Here is a VBA solution that uses multidimensional arrays. I noticed you said you are a bit new to VBA so I tried to put some meaningful comments in there. One thing that might look strange is when I redimension the arrays. That's because when you have multidimensional arrays you can only ReDim the last dimension in the array when you use the Preserve keyword.

    Here is how my data looked:

    Product Count
    101     1
    102     1
    101     2
    102     2
    107     7
    101     4
    101     4
    189     9
    

    And here is the code. It has the same output as my last answer. Test this in a new workbook and put the test data in Sheet1 with headers.

    Option Explicit
    
    Sub testFunction()
        Dim rng As Excel.Range
        Dim arrProducts() As String
        Dim i As Long
    
        Set rng = Sheet1.Range("A2:A9")
    
        arrProducts = getSumOfCountArray(rng)
    
        Sheet2.Range("A1:B1").Value = Array("Product", "Sum of Count")
    
        ' go through array and output to Sheet2
        For i = 0 To UBound(arrProducts, 2)
            Sheet2.Cells(i + 2, "A").Value = arrProducts(0, i)
            Sheet2.Cells(i + 2, "B").Value = arrProducts(1, i)
        Next
    
    End Sub
    
    ' Pass in the range of the products
    Function getSumOfCountArray(ByRef rngProduct As Excel.Range) As String()
        Dim arrProducts() As String
        Dim i As Long, j As Long
        Dim index As Long
    
        ReDim arrProducts(1, 0)
    
        For j = 1 To rngProduct.Rows.Count
            index = getProductIndex(arrProducts, rngProduct.Cells(j, 1).Value)
            If (index = -1) Then
                ' create value in array
                ReDim Preserve arrProducts(1, i)
                arrProducts(0, i) = rngProduct.Cells(j, 1).Value ' product name
                arrProducts(1, i) = rngProduct.Cells(j, 2).Value ' count value
                i = i + 1
            Else
                ' value found, add to id
                arrProducts(1, index) = arrProducts(1, index) + rngProduct.Cells(j, 2).Value
            End If
        Next
    
        getSumOfCountArray = arrProducts
    End Function
    
    Function getProductIndex(ByRef arrProducts() As String, ByRef strSearch As String) As Long
        ' returns the index of the array if found
        Dim i As Long
        For i = 0 To UBound(arrProducts, 2)
            If (arrProducts(0, i) = strSearch) Then
                getProductIndex = i
                Exit Function
            End If
        Next
    
        ' not found
        getProductIndex = -1
    End Function
    

提交回复
热议问题