• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Sorting in VBA Arrays

AAP

Member
Hi,
I have an two dimensional array and I would like to sort that but couldn't understand how to achieve sorting in array.
I know this can be easily achieved in worksheet but I would like to learn sorting in arrays.
Can anyone help me with this.
Sample file attached.

Thanks a lot!
 

Attachments

  • Array Sorting.xlsm
    14.8 KB · Views: 0
Hi,

as there is no VBA sort method for an array variable, you need an
algorithm like ComboSort with few data or QuickSort with huge data
(see on Wiki and many samples over the Web in VBA).

Other way is to use a SortedList ActiveX like in the thread
Unique names and their related IDs
 
Code:
Sub Demo()
  VA = Sheet1.[B5].CurrentRegion.Value
  Application.ScreenUpdating = False
  Sheet2.Range("B5", Sheet2.Cells(Rows.Count, 3).End(xlUp)).Clear
With CreateObject("System.Collections.SortedList")
  For R& = 2 To UBound(VA)
  .Item(VA(R, 2)) = .Item(VA(R, 2)) & " " & VA(R, 1)
  Next
  R = 5
   
  For L% = 0 To .Count - 1
  Sheet2.Cells(R, 2).Value = .GetKey(L)
  For Each V In Split(LTrim(.GetByIndex(L)))
  R = R
  Sheet2.Cells(R, 3).Value = V
  Next
  R = R + 1
  Next
  .Clear
End With
  Application.Goto Sheet2.Cells(1), True
  Application.ScreenUpdating = True
End Sub

This code works for me but how to sort descending in order.
I guess this line (For L% = 0 To .Count - 1) will do work but couldn't understand L% means.
 

Descending way : For L% = .Count - 1 To 0 Step -1

% means the data type, just check in VBE Locals window !
 
Data Types, Type Character

Integer, %
Long, @
Single; !
Double, #
String, $
Currency, @

So
Dim myVar as String
can be simplified to
Dim myVar$

Sometimes in VBA you will type 0 and VBA displays 0#
This is because it is declaring that it is a value type Double with a value of 0
 
Back
Top