Excel VBA解读(151): 数据结构——增强集合功能的代码

论坛 期权论坛 期权     
完美Excel   2019-7-27 14:44   9138   0
学习Excel技术,关注微信公众号:
excelperfect

集合是一种很有用的数据结构,能够让我们更方便地实现一些程序功能。本文介绍几段代码,能够进一步增强集合的功能。

判断键值是否存在
在集合中,没有内置方法判断键是否已存在。下面的代码检查指定的键是否已存在:
Function KeyIsExists(col AsCollection, key As String) As Boolean
   On Error GoTo ExitHere
   col.Item key
   KeyIsExists = True
ExitHere:
End Function

测试KeyIsExists函数的代码如下:
Sub testKey()
   Dim colMy As New Collection
   colMy.Add Item:="完美Excel", key:="excelperfect"
   colMy.Add Item:="微信公众号", key:="weixin"
   
   Debug.Print KeyIsExists(colMy, "excelperfect")
   Debug.Print KeyIsExists(colMy, "me")
End Sub

运行结果如下图1所示。


图1

对集合元素进行排序
在集合中,没有内置的排序方法。这里,使用快速排序算法来对集合中的元素排序:
Sub SortToCollection(col AsCollection, lFirst As Long, lLast As Long)
   Dim vMiddle As Variant, vTemp As Variant
   Dim lTempLow As Long
   Dim lTempHi As Long

   lTempLow = lFirst
   lTempHi = lLast
   vMiddle = col((lFirst + lLast) \ 2)
   
   Do While lTempLow  lFirst
            lTempHi = lTempHi - 1
        Loop
   
        If lTempLow
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:195
帖子:39
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP