'VBA Userform Scrollable Listbox displaying incorrect value
In a userform that I create, I add a scrollable listbox (2 columns, 7 rows)and a button.
When I click the button, the value in the third column should change, and the listbox should display the new value accordingly.
However, currently there are particular rows fail to display the new value even I change it already. And I also notice that the rows that fail to display the new value are those not showing in the scrollable list box when I click the button.
Below is an example that I create to demonstrate my problem. As you can see, I click the button once which increase the second column of each row by 1 successfully. Screenshot1 Screenshot2
However, when I click the button second time, the rows that are not display in the scrollable listbox at the moment, fail to increase by 1 again. Screenshot3 Screenshot4
Below is the code I used in the example.
Private Sub CommandButton1_Click()
For i = 0 To lstProducts.ListCount - 1
lstProducts.List(i, 1) = lstProducts.List(i, 1) + 1
Next i
End Sub
Private Sub UserForm_Initialize()
Dim iCell As Long
VBA.Randomize
With lstProducts
.ColumnCount = 2
.ColumnWidths = "120;60;50"
.List = Worksheets("Product").Range("a1").CurrentRegion.Value
End With
End Sub
Does anyone know why this happen. Thank you so much!!!
Solution 1:[1]
Replace your loop with this code
x = lstProducts.TopIndex
For i = 0 To lstProducts.ListCount - 1
lstProducts.ListIndex = i
lstProducts.List(i, 1) = lstProducts.List(i, 1) + 1
Next i
lstProducts.ListIndex = x
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
