Search code examples
excelvba

How can I loop thru two columns of grouped values in Excel VBA and create a helper column that identifies the differences/similarities per each group?


I'm trying to loop through a list of Group IDs in column A and Division IDs in column B and return the values as shown in column C (please see below picture).

If the Division value in column B is different (not all the same) for that given Group ID in column A, return a value called: "MIXED" for the entire group in column C, where it's the same, return a value of "SAME" etc. (please see below picture).

Thank you!

enter image description here


Solution

  • Microsoft documentation:

    Dictionary object

    Option Explicit
    Sub Demo()
        Dim objDic As Object, objDic2 As Object, rngData As Range
        Dim i As Long, sKey As String
        Dim arrData
        Set objDic = CreateObject("scripting.dictionary")
        Set objDic2 = CreateObject("scripting.dictionary")
        Set rngData = Range("A1").CurrentRegion
        ' Load data into an array
        arrData = rngData.Value
        ' Loop through data
        For i = LBound(arrData) + 1 To UBound(arrData)
            sKey = arrData(i, 1)
            If objDic.exists(sKey) Then
                If Not objDic(sKey) = arrData(i, 2) Then
                    objDic2(sKey) = "Mixed"
                Else
                    If objDic2(sKey) = "Unique" Then
                        objDic2(sKey) = "Same"
                    End If
                End If
            Else
                objDic(sKey) = arrData(i, 2)
                objDic2(sKey) = "Unique"
            End If
        Next i
        ' Update the 3rd col
        For i = LBound(arrData) + 1 To UBound(arrData)
            arrData(i, 3) = objDic2(arrData(i, 1))
        Next i
        ' Write output to sheet
        rngData.Value = arrData
    End Sub
    
    

    enter image description here