excel vba array sort

'VBA does not include a built-in method for sorting arrays like many
'languages do.

'However, it is easy to have VBA create and use a .NET ArrayList for sorting.

'***THE MAJOR REASON TO USE ARRAYLIST IN VBA IS SORTING***

Set arrList = CreateObject("System.Collections.ArrayList")
    arrList.Add 4
    arrList.Add 2
    arrList.Add 1
    arrList.Add 3
  	arrList.Sort				'<--Sort() uses the QuickSort algorithm
  	arr = arrList.toArray		'<--toArray() creates a zero-based VBA array
 	MsgBox Join(arr, ",")		'<--displays: 1,2,3,4
  	arrList.Reverse				'<--Sort() uses the QuickSort algorithm
    arr = arrList.toArray
 	MsgBox Join(arr, ",")		'<--displays: 4,3,2,1

'ArrayList interrogation:  
MsgBox arrList.Count			'<--displays: 4.  Count() returns 0 if Stack empty
MsgBox arrList.Contains("Hi")	'<--displays: False

    arrlist.Remove 3
    arr = arrlist.toArray
    Debug.Print Join(arr, ",")	'<--displays: 4,2,1
  
  
'Clone the ArrayList:
Set arrlist2  = arrlist.Clone	'<--arrlist2 is not affected by ops on arrlist
    
'Empty the ArrayList:
arrlist.Clear  					'<--arrlist now empty, but can take a new Add()


'NB:    ArrayLists do not need to be dimensioned or redim'd like VBA arrays.    
'NB:	ArrayList elements can hold simple values as well as complex objects.
    
'Reference: 
'    https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist
 

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source