Ascending, descending order of VBA arrays

Source: Internet
Author: User
Tags arrays sort

① an ascending sort of VBA array

Function up (x ()) as Variant ()

Dim I As Integer, J As Integer, A, D ()

ReDim SX (LBound (x) to UBound (x)), D (LBound (x) to UBound (x))

D = x

If LBound (x) = UBound (x) Then

SX = d

Exit Function

End If

For i = LBound (x) to UBound (x)-1

For j = i + 1 to UBound (x)

If D (j) < D (i) Then

A = d (j): D (j) = d (i): D (i) = a

End If

Next

Next

SX = d

End Function

Descending sort of ②vba array

Function Down (x ()) as Variant ()

Dim I As Integer, J As Integer, A, D ()

ReDim SX (LBound (x) to UBound (x)), D (LBound (x) to UBound (x))

D = x

If LBound (x) = UBound (x) Then

SX = d

Exit Function

End If

For i = LBound (x) to UBound (x)-1

For j = i + 1 to UBound (x)

If d (j) > D (i) Then

A = d (j): D (j) = d (i): D (i) = a

End If

Next

Next

SX = d

End Function

③ array sorting for Chinese characters

If you want to sort on a character array, refer to the following code

Sub Start () Dim arr () as Variant arr = Array ("Large", "public", "meter", "Count", "Machine", "Learn", "XI", "net")

QuickSort2 arr (), 0, UBound (arr) Dim s as String for I = 1 to UBound (arr) s = S & Arr (I) & "|" Next MsgBox S

End Sub Sub QuickSort2 (MyArray () as Variant, L, R) Dim TP = 1

Dim I, J, x, Y i = L j = R X = MyArray ((L + R)/2) while (I <= J) while (StrComp (MyArray (i), X, TP) < 0 and I < R) i = i + 1 wend while (StrComp (X, MyArray (j), TP) < 0 and J > L) J = J-1 Wend If (i <= J) Then Y = MyArray (i) MyArray (I) = MyArray (j) myarray (j) = Y i = i + 1 J = J-1 end If giterations = giterations + 1 Wend

if (L < J) Then call QuickSort2 (MyArray (), L, J) if (I < R) Then call QuickSort2 (MyArray (), I, R)

End Sub

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.