I am trying to add items to a listbox in a Userform using a Command Button in Excel VBA. The tricky part is that said items should be grouped if the user clicks the button more than once (adding the same item more than once). For example, the first button is named cmdItem1 and has Item 1 as its caption. The listbox is named lstSaleDetail and has two columns, one of them is supposed to register the item's name and the second one its quantity, which starts at 1.
So, the first time any of the buttons is clicked, a new row is added to the listbox with a quantity of 1. But, the second (o any other) time the same button is clicked, instead of adding a new row with a quantity of 1, I want the existing row to update and show a quantity of 2. For this, I tried the following code:
Private Sub cmdItem1_Click()
If lstSaleDetail.ListCount > 0 Then
For i = 0 To (lstSaleDetail.ListCount - 1)
If cmdItem1.Caption = lstSaleDetail.List(i) Then
lstSaleDetail.List(i, 1) = lstSaleDetail.List(i, 1) + 1
Else
lstSaleDetail.AddItem
lstSaleDetail.List(lstSaleDetail.ListCount - 1, 0) = cmdItem1.Caption
lstSaleDetail.List(lstSaleDetail.ListCount - 1, 1) = "1"
End If
Next i
Else
lstSaleDetail.AddItem
lstSaleDetail.List(lstSaleDetail.ListCount - 1, 0) = cmdItem1.Caption
lstSaleDetail.List(lstSaleDetail.ListCount - 1, 1) = "1"
End If
End Sub
This only works if the listbox is empty, in which case the code works perfectly. However, if any other items are added (hence there is more than one row) the code breaks. Although the first row containing the information of the clicked item keeps increasing its quantity the way it should, new rows of the same item are also added and that should not be happening. Any suggestions of what could be wrong with my code?
As a clarification, I added the If lstSaleDetail.ListCount > 0 Then condition because otherwise none of the code works when the listbox is empty.