0

我正在使用冒泡排序功能按对象的属性对对象进行排序。不幸的是,我不得不为每个属性编写一个函数。有什么方法可以概括以下功能。

而不是写

SortArticlesByVolume(a)
SortArticlesByLenght(a)

我想写一些类似的东西:

SortArticles(a, volume)

Sub SortArticlesByVolume(ByRef 文章作为变体)

Dim sorted As Boolean
Dim i As Integer

sorted = False
Do While Not sorted
    sorted = True
    For i = 0 To UBound(articles) - 1
        If articles(i).volume < articles(i + 1).volume Then
            Set temp = articles(i + 1)
            Set articles(i + 1) = articles(i)
            Set articles(i) = temp
            sorted = False
        End If
    Next i
Loop

结束子

Sub SortArticlesBylenght(ByRef 文章作为变体)

Dim sorted As Boolean
Dim i As Integer

sorted = False
Do While Not sorted
    sorted = True
    For i = 0 To UBound(articles) - 1
        If articles(i).lenght < articles(i + 1).lenght Then
            Set temp = articles(i + 1)
            Set articles(i + 1) = articles(i)
            Set articles(i) = temp
            sorted = False
        End If
    Next i
Loop

结束子

4

1 回答 1

1

我不认为 VBA 允许您使用反射,所以我想您需要重写您的文章类并添加方法来按名称获取属性,例如article.get("volume")获取音量。如果您没有太多字段,这可能是最简单的方法。get 函数仍然需要某种 Select 或 If/Then 语句,但它会被封装在类本身中。

于 2012-03-26T15:04:08.087 回答