我试图对从单元格A40开始到A46结尾的7列值进行排序。我正在使用冒泡排序,我创建了两个程序。但是,当我执行时,VBA告诉我下标超出范围......有人能告诉我我的代码中的问题在哪里吗?
Sub dort()
Dim plaga() As Variant
plaga = Worksheets("Sheet3").Range("A40:A46").Value
Call tri1(plaga)
Dim Destination As Range
Set Destination = Worksheets("Sheet3").Range("C40")
Destination.Resize(7, 1).Value = plaga
End Sub
Sub tri1(plaga As Variant)
Dim ligne_Deb As Long
Dim ligne_Fin As Long
ligne_Deb = LBound(plaga)
ligne_Fin = UBound(plaga)
Dim i As Long, j As Long
Dim tmp As Long
For i = ligne_Deb To ligne_Fin - 1
For j = ligne_Fin To i + 1 Step -1
If plaga(j) < plaga(j - 1) Then
tmp = plaga(j)
plaga(j) = plaga(j - 1)
plaga(j - 1) = tmp
End If
Next j
Next i
End Sub
答案 0 :(得分:2)
有人能告诉我我的代码中的问题在哪儿吗?
plaga = Worksheets("Sheet3").Range("A40:A46").Value
在数组中存储范围时,它不是单维数组。
将您的代码更改为
plaga(j,1)
注意,1
。把它放在每个地方。
例如
For i = ligne_Deb To ligne_Fin - 1
For j = ligne_Fin To i + 1 Step -1
If plaga(j, 1) < plaga(j - 1, 1) Then
tmp = plaga(j, 1)
plaga(j, 1) = plaga(j - 1, 1)
plaga(j - 1, 1) = tmp
End If
Next j
Next i