简体   繁体   中英

Sort 2D array in Excel VBA

Good day,

I am trying to sort a 2D array, based on the contents of the first column. I found this code for "QuickSortArray" which seem to be the solution:

Sorting a multidimensionnal array in VBA

Although I can't make it work for my example. My example is:

Sub test()

Dim TestArray1(1 To 4, 0 To 1) As Variant
Dim TestArray2

TestArray1(1, 0) = 108
TestArray1(2, 0) = 109
TestArray1(3, 0) = 106
TestArray1(4, 0) = 110

TestArray1(1, 1) = 10
TestArray1(2, 1) = 5
TestArray1(3, 1) = 15
TestArray1(4, 1) = 2

TestArray2 = QuickSortArray(TestArray1, , , 2)

Debug.Print TestArray2(2, 1)

End Sub

I try to sort the array, based on the first or second column.

The error is:

expecting function or variable.

Do you know what is wrong with my example?

QuickSortArray is a Sub not a function and it cannot be assigned to variable like this:

TestArray2 = QuickSortArray(TestArray1, , , 2)

In order to make your code working you need to modify it like below:

Sub test()

    Dim TestArray1(1 To 4, 0 To 1) As Variant
    Dim TestArray2

    TestArray1(1, 0) = 108
    TestArray1(2, 0) = 109
    TestArray1(3, 0) = 106
    TestArray1(4, 0) = 110

    TestArray1(1, 1) = 10
    TestArray1(2, 1) = 5
    TestArray1(3, 1) = 15
    TestArray1(4, 1) = 2

    TestArray2 = TestArray1
    Call QuickSortArray(TestArray2, , , 2)

    Debug.Print TestArray2(2, 1)

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM