按唯一字母顺序自定义排序

时间:2019-11-08 06:08:38

标签: excel vba

我正在尝试按照唯一的字母顺序进行自定义排序,以精确地按以下顺序排序。最好使用vba解决方案。

A, P, R, C, D, E, F, G, H, I, J, K, L, M, O, Q, S, T, U, V, W, X, Y, Z, B, N

谢谢 苏吉

1 个答案:

答案 0 :(得分:1)

这很简单:

  1. 使用自定义顺序定义数组
  2. 基于该数组进行比较:查找字母索引并返回这些索引的差值,然后,如果resut> 0,则第二个参数更大,<0-第一个更大,= 0 =两者相等。< / li>

请参见以下代码:

Option Explicit

Sub CustomOrder()
    MsgBox CustomComparer("Z", "B") 'shows 1, so B is greater
End Sub

Function CustomComparer(str1 As String, str2 As String) As Long
    Dim orderArray As Variant
    orderArray = Array("A", "P", "R", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "O", "Q", "S", "T", "U", "V", "W", "X", "Y", "Z", "B", "N")

    Dim isFirstFound As Boolean, isSecondfound As Boolean, i As Long, firstIndex As Long, secondIndex As Long

    For i = LBound(orderArray) To UBound(orderArray)
        If str1 = orderArray(i) Then
            firstIndex = i
            isFirstFound = True
        End If
        If str2 = orderArray(i) Then
            secondIndex = i
            isSecondfound = True
        End If
        If isFirstFound And isSecondfound Then Exit For
    Next

    CustomComparer = secondIndex - firstIndex
End Function