VBA: Sort array based on another array

后端 未结 1 1885
甜味超标
甜味超标 2021-01-20 13:06

I have several very long arrays which needs to be sorted alphabetically based on user action, but for simplicity I\'ll use the following example:

Dim Name as         


        
1条回答
  •  攒了一身酷
    2021-01-20 13:16

    This appears to do what you want:

    Sub MAIN()
        Dim Name(), Street()
        Name = Array("B", "C", "D", "A", "E")
        Street = Array("1", "2", "3", "4", "5")
    
        Call sort2(Name(), Street())
    
        For Each s In Street
            MsgBox s
        Next s
    End Sub
    
    
    Sub sort2(key() As Variant, other() As Variant)
    Dim I As Long, J As Long, Low As Long
    Dim Hi As Long, Temp As Variant
        Low = LBound(key)
        Hi = UBound(key)
    
        J = (Hi - Low + 1) \ 2
        Do While J > 0
            For I = Low To Hi - J
              If key(I) > key(I + J) Then
                Temp = key(I)
                key(I) = key(I + J)
                key(I + J) = Temp
                Temp = other(I)
                other(I) = other(I + J)
                other(I + J) = Temp
              End If
            Next I
            For I = Hi - J To Low Step -1
              If key(I) > key(I + J) Then
                Temp = key(I)
                key(I) = key(I + J)
                key(I + J) = Temp
                Temp = other(I)
                other(I) = other(I + J)
                other(I + J) = Temp
              End If
            Next I
            J = J \ 2
        Loop
    End Sub
    

    EDIT#1:

    To add more arrays to the mix, just include them in the header and insert more lines like:

                Temp = other2(I)
                other2(I) = other2(I + J)
                other2(I + J) = Temp
    

    in both places in the sort routine.

    0 讨论(0)
提交回复
热议问题