2008-04-28

如何將產品依數量遞減排序?


問題:


我有三個 CheckBox,分別為三種產品的核取選項,勾選時會自動累計該產品數量,按 CommandButton 後會將三種產品依數量遞減排序,並顯示於 Label 上。

Ex: 產品 A = 5, 產品 B = 4, 產品 C = 3

請問程式應該怎麼寫?


回答:

假設產品名稱及數量存放在以下陣列變數裡:
Dim ProdName(2) As String
Dim ProdQty(2) As Long

請在 CommandButton 的 Click 事件程序裡加入以下程式碼:

Private Sub Command1_Click()
 Dim ProdRank(2) As Integer, TmpRank As Integer
 Dim i, j As Integer

 ' ProdRank 存放的是產品的索引位置,一開始設定它們的數量排名順序和索引位置相同
 For i = 0 to 2
  ProdRank(i) = i
 Next

 ' 再依照產品實際的數量逐一調整它們的順序
 For i = 0 to 1
  For j = i 1 To 2
   If ProdQty(ProdRank(i)) <>
    TmpRank = ProdRank(i)
    ProdRank(i) = ProdRank(j)
    ProdRank(j) = TmpRank
   End If
  Next
 Next

 ' 將排序結果以 Label1 顯示
 Label1 = ""
 For i = 0 to 2
  Label1 = Label1 & ProdName(ProdRank(i)) & " = " & Cstr(ProdQty(ProdRank(i))) & vbCrlf
 Next
End Sub

沒有留言: