How to sort a two-dimensional string array?
My array is declared by
Code:
Dim vArray As Object
vArray = oXLSheet.Range("B2:C201").Value
It looks like
1,1
1,2
2,1
2,2
3,1
3,2
.
.
.
199,1
199,2
200,1
200,2
I don't know why it starts at 1 and not 0 but that doesn't concern me.
I would like to sort the array by the second dimension, i.e. using the values in
1,2
2,2
3,2
and so on.
Both dimensions are strings. Obviously the values of 1,1 and 1,2 must stay together.
Can anyone help?
Re: How to sort a two-dimensional string array?
You have two options:
1. Implement a sorting algorithm yourself. Just loop through the array by "row" and compare the values in the second column. If you need to swap two values then you swap the values in the first "column" and the values in the second "column".
2. Define a type that represents a "row". Loop through the array by "row" and create instances of that type and add them to a List. Call the List's Sort method and provide an appropriate IComparer or Comparison, or else you can implement IComparable in your type and let them compare themselves. When you're done, loop through the List and repopulate the array.
If you choose the second option then you can follow the Blog link in my signature and check out my posts on sorting collections and arrays.
Re: How to sort a two-dimensional string array?
Another thought just occurred to me. Since my array comes from an excel spreadsheet is it possible to sort the spreadsheet in vb because excel can keep the values together when it sorts ("expand the selection").
Re: How to sort a two-dimensional string array?
Quote:
Originally Posted by
natrap
Another thought just occurred to me. Since my array comes from an excel spreadsheet is it possible to sort the spreadsheet in vb because excel can keep the values together when it sorts ("expand the selection").
I'm sure it would be but I'm no Office developer so I'll leave that to others. That said, my first guess would be that Range would return an object that supports such functionality so you might try seeing what Intellisense can give you.
Re: How to sort a two-dimensional string array?
Thanks for the tips. I actually found a much simpler way. I copied the array into a SortedList which does exactly what I was after.