Home » excel » Excel VBA multi column listbox add item on top

Excel VBA multi column listbox add item on top

Posted by: admin May 14, 2020 Leave a comment

Questions:

All,

is there any easy way to add item at begining of listbox?

I found some information about insert function but it seems to be not available in Excel VBA.

Only way I found is to create FOR which will move each row to +1 postion and then insert item at 0 index. I was really hoping there is a easier way.

My long version looks like this:

SSub InsertRecordAtTheTop(sText1, sText2)
Dim i
With lbCases
If .ListCount > -1 Then
.AddItem "0" ''' add new row
For i = .ListCount - 1 To 1 Step -1 ''' move everything +1 postion
.List(i, 0) = .List(i - 1, 0)
.List(i, 1) = .List(i - 1, 1)
.List(i, 2) = .List(i - 1, 2)
.List(i, 3) = .List(i - 1, 3)
.List(i, 4) = .List(i - 1, 4)
Next i
.List(0, 0) = sText1 ''' paste new values at top
.List(0, 1) = sText2
.List(0, 2) = ""
.List(0, 3) = ""
.List(0, 4) = ""
Else
.AddItem sText1 ''' if listbox is empty, just paste
.List(0, 1) = sText2
End If
End With
End Sub

Thanks,
TJ

How to&Answers:

AddItem takes an optional parameter to specify the index position. By default it adds to the end. If you specify 0 it will add at the beginning. Try Something like:

.AddItem "Some Text", 0

More information can be found in this MSDN article.