VBA - Error 9: subscript out range - Why does this error occur in my code?

elinoiz

New Member
Joined
May 21, 2016
Messages
5
Hi all,
I'm a total newbie in VBA, so while trying to do a bubble sort routine, I was constantly getting an error 9: Subscript out of range. After I added an optional rank in LBound() function, it worked, but I don't understand why.
Could someone explain why does the second code work, while first one doesn't?

Array is: 59, 71, 82, 7, 10, 16, 25, 29, 1, 3, 49, 30

Original code which doesn't work:
Private Sub BubbleSrtTest()
Dim Temp As Variant
Dim i As Long
Dim j As Long
Dim SrtArray As Variant


SrtArray = Selection.Value


For i = LBound(SrtArray) To UBound(SrtArray) - 1
For j = i + 1 To UBound(SrtArray)
If SrtArray(i) > SrtArray(j) Then
Temp = SrtArray(j)
SrtArray(j) = SrtArray(i)
SrtArray(i) = Temp
End If
Next j
Next i

Selection.Value = SrtArray
End Sub

Code which does work:
Private Sub BubbleSrtTest()
Dim Temp As Variant
Dim i As Long
Dim j As Long
Dim SrtArray As Variant


SrtArray = Selection.Value


For i = LBound(SrtArray, 1) To UBound(SrtArray, 1) - 1
For j = i + 1 To UBound(SrtArray, 1)
If SrtArray(i, 1) > SrtArray(j, 1) Then
Temp = SrtArray(j, 1)
SrtArray(j, 1) = SrtArray(i, 1)
SrtArray(i, 1) = Temp
End If
Next j
Next i
Selection.Value = SrtArray
End Sub
 
When you populate an array from a range, which I'm assuming Selection is, you end up with an array with 2 dimensions.

In the code you posted that doesn't work you are missing the 2nd dimension when referring to items in the array.
 
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top