Search code examples
excelvbams-accessexcel-2010

Add Same Items In ListBox


I have been searching for solutions on the internet for sometime but to no avail. I want to write a procedure that will run through the columns of a listbox and sum up all values that have similar names compared to a name found in a textbox (TextBox1) i have on my userform.

I have tried the following code but its not working as perfectly as i want

`

 Dim i As Integer
 Dim mySum As Double
 mySum = 0

 If Me.ListBox1.Column(i, 0) = Me.TextBox1.value And Me.ListBox1.Column(i, 0) <> "" Then
 For i = 0 To Me.ListBox1.ListCount - 1
 mySum = mySum + Me.ListBox1.List(i, 2)
 Next i
 Me.TextBox4.value = Format(mySum, "#,##0.00")

 End If
 End Sub`

It works alright but instead of adding values in the third column that have similar values in the first column that can be found in TextBox1, it sums up all the values in the third column


Solution

  • It looks like the logic in your code is not quite right - the If condition should be inside the For loop, the following should work:

    For i = 0 To Me.ListBox1.ListCount - 1
        If Me.ListBox1.List(0, i) = Me.TextBox1.Value And Me.ListBox1.List(0, i) <> "" Then
            mySum = mySum + Me.ListBox1.List(i, 2)
        End If
    Next i