在 VBA 中对列表框进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3180331/
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
sorting a listbox in VBA
提问by masfenix
I have a listbox with values. Now I need to sort that listbox, BUT NOT BY ALPHABETICALLY.
我有一个带有值的列表框。现在我需要对该列表框进行排序,但不是按字母顺序排序。
You see the values in a listbox are from a table.
您会看到列表框中的值来自表格。
------------------------
| name | order | size |
========================
value1 4
value2 3
value3 1
value4 2
I hope I made myself clear. So the list box has the items "value1, value2, value3, value4". I want it to sort by the order declared in the table. The list box has nothing to do with the table and is not "data bound" to it. The values come from somewhere else.
我希望我说清楚了。所以列表框有项目“value1、value2、value3、value4”。我希望它按表中声明的顺序排序。列表框与表无关,也不是“数据绑定”到它。这些值来自其他地方。
Tech used: VBA, Access 2007
使用的技术:VBA、Access 2007
采纳答案by HansUp
It sounds like the Row Source Typefor your list box is "Value List". Since the values come from a table, change Row Source Typeto "Table/Query", then use a query for Row Source:
听起来您的列表框的行源类型是“值列表”。由于值来自表,将Row Source Type更改为“Table/Query”,然后对Row Source使用查询:
SELECT [name], [order]
FROM YourTable
ORDER BY [order];
You don't have to display [order] in the list box ... set its column width to zero.
您不必在列表框中显示 [order] ...将其列宽设置为零。
Your list box control does not have to be bound to a data source field for this approach to work. If the list box is unbound, the user selection will not be stored, but the list box will still allow users to make selections from the list box.
您的列表框控件不必绑定到数据源字段以使用此方法。如果列表框未绑定,则不会存储用户选择,但列表框仍允许用户从列表框中进行选择。
Notice I enclosed [name] and [order] in square brackets because both are reserved words. See Problem names and reserved words in Access
请注意,我将 [name] 和 [order] 括在方括号中,因为它们都是保留字。请参阅Access 中的问题名称和保留字
回答by Moon
Dim First As Integer
Dim Last As Integer
Dim a As Integer
Dim b As Integer
Dim Temp As String
Dim test() As String
First = LBound(test)
Last = UBound(test)
For a = First To Last - 1
For b = a + 1 To Last
If test(a) > test(b) Then
Temp = test(b)
test(b) = test(a)
test(a) = Temp
End If
Next b
Next a
For a = 1 To UBound(test)
lst_email.AddItem test(a) 'lst_email is a listbox
Next