Excel VBA 多列列表框在顶部添加项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25954954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:36:56  来源:igfitidea点击:

Excel VBA multi column listbox add item on top

excelvbaexcel-vbalistbox

提问by Tomasz Jaszczuk

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.

我找到了一些关于插入函数的信息,但它似乎在 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.

我发现的唯一方法是创建 FOR,它将每行移动到 +1 位置,然后在 0 索引处插入项目。我真的希望有一种更简单的方法。

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

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

谢谢,TJ

回答by Michael Petch

AddItemtakes 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接受一个可选参数来指定索引位置。默认情况下,它会添加到末尾。如果您指定 0,它将在开头添加。尝试类似的东西:

.AddItem "Some Text", 0

More information can be found in this MSDNarticle.

更多信息可以在这篇MSDN文章中找到。