Private Sub Command1_Click() Dim a As Variant a = Array(10, 5, 30, 450, 45, 78, 89, 4, 36) '排序 For i = 1 To 9 k = i For j = i + 1 To 10 If a(j) < a(k) Then k = j Next j If k <> i Then tmp = a(k) a(k) = a(i) a(i) = tmp End If Next i
End Sub 以上是我对10,5,30,450,45,78,89,4,36从小到大排序所编的程序,可是不能运行,为什么?
Option Explicit Dim i&, j&, k&, t&, a() Private Sub Form_Load() a = Array(10, 5, 30, 450, 45, 78, 89, 4, 36) Command1.Caption = "由小到大" Command2.Caption = "由大到小" End Sub
Private Sub Command1_Click() Me.Cls For i = 0 To UBound(a) k = i For j = i + 1 To UBound(a) If a(k) > a(j) Then k = j '大小排序的代码差别只在于 > 与 < Next j t = a(i): a(i) = a(k): a(k) = t Next i For i = 0 To UBound(a) Print a(i); Next i End Sub
Private Sub Command2_Click() Me.Cls For i = 0 To UBound(a) k = i For j = i + 1 To UBound(a) If a(k) < a(j) Then k = j Next j t = a(i): a(i) = a(k): a(k) = t Next i For i = 0 To UBound(a) Print a(i); Next i End Sub
'看懂上面大小排序的代码后, 再理解此简化方式的代码 '下面这个代码培养你代码共用的思维, 因为在其它用途上AB有可能是01234... 这时你就可以用Select Case
Option Explicit Dim i&, j&, k&, t&, a(), AB% Private Sub Form_Load() a = Array(10, 5, 30, 450, 45, 78, 89, 4, 36) Command1.Caption = "由小到大" Command2.Caption = "由大到小" End Sub
Private Sub Command1_Click() AB = 0 Call ShowResult End Sub
Private Sub Command2_Click() AB = 1 Call ShowResult End Sub
Sub ShowResult() Me.Cls For i = 0 To UBound(a) k = i For j = i + 1 To UBound(a) If AB = 0 Then If a(k) > a(j) Then k = j Else If a(k) < a(j) Then k = j End If Next j t = a(i): a(i) = a(k): a(k) = t Next i For i = 0 To UBound(a) Print a(i); Next i End Sub
'先添加Command1 复制粘贴Command1此时会提示创建控件数组吗?你选择 是 '当然你可以在属性窗里面直接设置 index 值
'本代码需要 Command1(0) 与 Command1(1)
Option Explicit Dim i&, j&, k&, t&, a()
Private Sub Form_Load() a = Array(10, 5, 30, 450, 45, 78, 89, 4, 36) Command1(0).Caption = "由小到大" Command1(1).Caption = "由大到小" End Sub
Private Sub Command1_Click(Index As Integer) Call ShowResult(Index) End Sub
Sub ShowResult(AB%) Me.Cls For i = 0 To UBound(a) k = i For j = i + 1 To UBound(a) If AB = 0 Then If a(k) > a(j) Then k = j Else If a(k) < a(j) Then k = j End If Next j t = a(i): a(i) = a(k): a(k) = t Next i For i = 0 To UBound(a) Print a(i); Next i End Sub
Private Sub Form_Click() Dim a, atm As Variant Dim arry(9) As Integer arry(1) = 10: arry(2) = 5: arry(3) = 30: arry(4) = 450: arry(5) = 45: arry(6) = 78: arry(7) = 89: arry(8) = 4: arry(9) = 36
For i = 1 To 9 For j = i To 9 If arry(i) > arry(j) Then atm = arry(i) arry(i) = arry(j) arry(j) = atm End If Next j Next i For i = 1 To 9 Print arry(i) Next i 这样也可以呀
Private Sub Command1_Click() Dim a() As Variant a = Array(10, 5, 30, 450, 45, 78, 89, 4, 36) '排序 For i = 1 To 9 k = i For j = i + 1 To 9 If a(j) < a(k) Then k = j Next j If k <> i Then tmp = a(k) a(k) = a(i) a(i) = tmp End If Next i For i = 1 To 9 Print a(i) Next i End Sub