Gre*_*edo 4 sorting collections excel vba arraylist
是否有任何数据结构可以通过有效的对象排序和过滤来访问?
对于排序,这System.Collections.ArrayList是完美的,因为我只是添加了大量的类 whichImplement IComparable和.Sort(). 但是我找不到.Filter()方法,因为可能存在一些文章提示(第 9.3 节)。
是否有用于过滤和排序自定义对象的良好集合类型?最好是用预编译语言编写的东西。
一个简单的对象看起来像这样:
Implements IComparable 'requires mscorlib.dll, allows sorting
Public itemIndex As Long 'simplest, sorting by an integer value
Private Function IComparable_CompareTo(ByVal obj As Variant) As Long
'for sorting, itemindex is based on current grid sorting mode
If TypeOf obj Is clsGridItem Then
Dim other As clsGridItem: Set other = obj
Dim otherIndex As Long: otherIndex = other.itemIndex
Dim thisIndex As Long: thisIndex = Me.itemIndex
If thisIndex > otherIndex Then
IComparable_CompareTo = 1
ElseIf thisIndex < otherIndex Then
IComparable_CompareTo = -1
Else
IComparable_CompareTo = 0
End If
Else
Err.Raise 5 'obj is wrong type
End If
End Function
Run Code Online (Sandbox Code Playgroud)
我有一个用随机索引填充的数组列表。当然,任何东西都可以进入比较例程(我实际上Select Case用于不同的比较例程,基于类的不同属性)。一个简单的过滤器循环可以检查何时IComparable_CompareTo = 0
ArrayList 对象内置了排序功能,而过滤无非是“仅使用您需要的项目”。
例如,这会用随机数填充一个对象,然后过滤结果以仅显示那些可被 整除的结果42:
Option Explicit
Sub testSort()
Const filter = 42
Dim arr As Object, x As Long, y As Long
Set arr = CreateObject("System.Collections.ArrayList")
' populate array with 100 random numbers
For x = 1 To 420
arr.Add Int(Rnd() * 10000)
Next
' "sort" array
arr.Sort
' dump array to immediate window; "filter" to show only even numbers
For x = 0 To arr.Count - 1
If arr(x) / filter = arr(x) \ filter Then
'item mnatches filter
Debug.Print "arr(" & x & ") = " & arr(x)
y = y + 1
End If
Next x
Debug.Print "Returned " & y & " sorted results (Filter=" & filter & ")"
End Sub
Run Code Online (Sandbox Code Playgroud)
您还没有共享的细节是什么,你需要过滤器和如何,但我进一步思考它,你可能要检查这些了,看他们是否可以应用到你的任务:
MSDN:过滤器函数(VBA)
根据指定的过滤条件返回包含字符串数组子集的从零开始的数组
excelfunctions.net:过滤函数(VBA)
MSDN:过滤集合中的项目(VBA)
msdocs: CreateObject("System.Collections.ArrayList")(VB)
根据指定类型过滤 IEnumerable 的元素
msdocs:ArrayList类构造函数(VB)
堆栈溢出:如何在 Visual Basic 中实现类构造函数?(VB)
堆栈溢出:VBA 数组排序函数(VB/VBA)
维基百科:流行排序算法的比较
| 归档时间: |
|
| 查看次数: |
519 次 |
| 最近记录: |