首页 > 解决方案 > 通过增加数字顺序对数组进行排序

问题描述

出于某种原因,以下函数不是按数字排序数组,而是按字符串值排序。一个数组

1
7
9
15
18
6
14
17
16

被分类为

1
14
15
16
17
18
19
6
7
9

这是代码:

    For i = LBound(months_array) To UBound(months_array) - 1
        For j = i + 1 To UBound(months_array)
            If UCase(months_array(i)) > UCase(months_array(j)) Then
                Temp = months_array(j)
                months_array(j) = months_array(i)
                months_array(i) = Temp
            End If
        Next j
    Next i

我检查了元素的数据类型,它们似乎是数字的——虽然我无法完全验证

标签: vba

解决方案


如果您的数组元素是数字,那么为什么要使用 UCase() ?

除了直接比较之外,您不需要任何东西:

For i = LBound(months_array) To UBound(months_array) - 1
    For j = i + 1 To UBound(months_array)
        If months_array(i) > months_array(j) Then
            Temp = months_array(j)
            months_array(j) = months_array(i)
            months_array(i) = Temp
        End If
    Next j
Next i

推荐阅读