Hi Guys,
I have been trying to sort a two-dimensional array in excel using VBA.
the values of the array are all strings not numbers, which has been causing my head to explode.
I have an excel sheet that contains data 4 rows by 4 columns.
I then want to put that data in to an array so I can use it.
This is the first time I have been playing with 2D Arrays in VBA. From what I gathered this is how it should look:
so going by this principal i tried to sort the array by the 2nd column. I tried various examples from other sites but they all say that "subscript out of range"
can anyone please let me know if I am going about this completely the wrong way. Any help greatly appreciated. Thanks
I have been trying to sort a two-dimensional array in excel using VBA.
the values of the array are all strings not numbers, which has been causing my head to explode.
I have an excel sheet that contains data 4 rows by 4 columns.
I then want to put that data in to an array so I can use it.
This is the first time I have been playing with 2D Arrays in VBA. From what I gathered this is how it should look:
Code:
Dim MyArray(1 To 4, 1 To 4)
MyArray(1, 1) = "A col1 row1"
MyArray(1, 2) = "C col1 row2"
MyArray(1, 3) = "D col1 row3"
MyArray(1, 4) = "B col1 row4"
MyArray(2, 1) = "D col2 row1 - sort this col"
MyArray(2, 2) = "B col2 row2 - sort this col"
MyArray(2, 3) = "A col2 row3 - sort this col"
MyArray(2, 4) = "C col2 row4 - sort this col"
MyArray(3, 1) = "A col3 row1"
MyArray(3, 2) = "D col3 row2"
MyArray(3, 3) = "B col3 row3"
MyArray(3, 4) = "C col3 row4"
MyArray(4, 1) = "D col4 row1"
MyArray(4, 2) = "C col4 row2"
MyArray(4, 3) = "B col4 row3"
MyArray(4, 4) = "A col4 row4"
can anyone please let me know if I am going about this completely the wrong way. Any help greatly appreciated. Thanks
Code:
Dim MyArray(1 To 4, 1 To 4)
Dim i As Integer, j As Integer
MyArray(1, 1) = "A col1 row1"
MyArray(1, 2) = "C col1 row2"
MyArray(1, 3) = "D col1 row3"
MyArray(1, 4) = "B col1 row4"
MyArray(2, 1) = "D col2 row1 - sort this col"
MyArray(2, 2) = "B col2 row2 - sort this col"
MyArray(2, 3) = "A col2 row3 - sort this col"
MyArray(2, 4) = "C col2 row4 - sort this col"
MyArray(3, 1) = "A col3 row1"
MyArray(3, 2) = "D col3 row2"
MyArray(3, 3) = "B col3 row3"
MyArray(3, 4) = "C col3 row4"
MyArray(4, 1) = "D col4 row1"
MyArray(4, 2) = "C col4 row2"
MyArray(4, 3) = "B col4 row3"
MyArray(4, 4) = "A col4 row4"
SortColumm1 = 1
SortColumn2 = 3
For i = LBound(MyArray, 1) To UBound(MyArray, 1) - 1
For j = LBound(MyArray, 1) To UBound(MyArray, 1) - 1
Condition1 = MyArray(j, SortColumn1) > MyArray(j + 1, SortColumn1)
Condition2 = MyArray(j, SortColumn1) = MyArray(j + 1, SortColumn1) And _
MyArray(j, SortColumn2) > MyArray(j + 1, SortColumn2)
If Condition1 Or Condition2 Then
For y = LBound(MyArray, 2) To UBound(MyArray, 2)
t = MyArray(j, y)
MyArray(j, y) = MyArray(j + 1, y)
MyArray(j + 1, y) = t
Next y
End If
Next
Next