Search code examples
vbalistboxoffsetuserform

VBA ListBox with Offset Columns


I'm using the following code to populate a ListBox. Column 1 of the ListBox comes from Column F of my worksheet, and the second column of the ListBox comes from the next column over. But I'm wanting to have that second ListBox column come from column D of the worksheet (2 to the left). And I just can't make the offset work the way I want.

    Private Sub UserForm_Initialize()

    Dim dic As Object
    Dim rng As Range
    Dim ky As Variant

    Set dic = CreateObject("Scripting.Dictionary")

    Set rng = Sheet4.Range("F2")

    Do
        If Not dic.exists(rng.Value) Then
            dic.Add rng.Value, rng.Offset(, 1).Value
        Else
            dic(rng.Value) = dic(rng.Value) + rng.Offset(, 1).Value
        End If
        Set rng = rng.Offset(1)
    Loop Until rng.Value = ""

    For Each ky In dic.keys
        With BWListBox3
            .AddItem
            .List(.ListCount - 1, 0) = ky
            .List(.ListCount - 1, 1) = Application.Text(dic(ky), "[h]:mm") 
        End With
    Next ky

End Sub

Solution

  • 2 to the left?

        If Not dic.exists(rng.Value) Then
            dic.Add rng.Value, rng.Offset(, -2).Value
        Else
            dic(rng.Value) = dic(rng.Value) + rng.Offset(, -2).Value
        End If