简体   繁体   中英

Why do I get Subscript out of range error for array

''' Doing a simple sort function '''

What am I doing wrong to receive 'Subscript out of range error" for the following code.

Dim Temp As Variant
    Dim Temp As Variant
    Dim i As Long
    Dim j As Integer
    Dim Arr() As Variant
    Arr = Range("B1:B4").Value
    
    For i = LBound(Arr) To UBound(Arr)
        For j = i + 1 To UBound(Arr)
          If Arr(i) > Arr(j) Then
            Temp = Arr(j)
            Arr(j) = Arr(i)
            Arr(i) = Temp
           End If
        Next j
    Next i

Arr = Range("B1:B4").Value creates a 4 Row X 1 Column two dimensional array. As such, you'll need to specify the second dimension...

Dim Temp As Variant
Dim i As Long
Dim j As Integer
Dim Arr() As Variant
Arr = Range("B1:B4").Value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM