返回列表 上一主題 發帖

[發問] ELSEIF與DO WHILE巢狀迴圈來判斷加總

本帖最後由 yen956 於 2014-4-15 09:57 編輯

回復 1# wiemanson
不知道你的意思是不是這樣?
執行結果:
紅        綠        藍        黃        All
3        5        1        5        10
如果是, 試試看:
Sub aa()
Dim x, sum1, sum2, sum3, sum4, sum5, sum6 As Long
x = 2
sum1 = 0
sum2 = 0
sum3 = 0
sum4 = 0
sum5 = 0
Do While Cells(x, 1) <> ""
    'If .. Else 具排他, 執行了 Cells(x, 4) = "新", 就不會執行其他的
    If Cells(x, 4) = "新" Then
    sum5 = sum5 + Cells(x, 2).Value
    End If
    '同樣 Cells(x, 3) = "大", 也不能在 IF...Else 內
    If Cells(x, 3) = "大" Then
    sum2 = sum2 + Cells(x, 2).Value
    End If
   
    If Cells(x, 1) = "紅" Then
    sum1 = sum1 + Cells(x, 2).Value
    ElseIf Cells(x, 1) = "紅紅" Then
    sum1 = sum1 + Cells(x, 2).Value
    ElseIf Cells(x, 1) = "綠" Then
    sum2 = sum2 + Cells(x, 2).Value
    ElseIf Cells(x, 1) = "藍" Then
    sum3 = sum3 + Cells(x, 2).Value
    ElseIf Cells(x, 1) = "黃" Then
    sum4 = sum4 + Cells(x, 2).Value
    Else
'沒作用吧?
    sum1 = sum1 + 0
    sum2 = sum2 + 0
    sum3 = sum3 + 0
    sum4 = sum4 + 0
    sum5 = sum5 + 0

    End If
    x = x + 1
Loop
Cells(3, 5) = sum1
Cells(3, 6) = sum2
Cells(3, 7) = sum3
Cells(3, 8) = sum4
Cells(3, 9) = sum5
End Sub
'但不知 "綠","大" 同排時, 你想怎麼處理?
又, sum1, sum2, sum3, sum4, sum5, sum6 一整排變數,
可直接用 [E3], [F3],[G3],... 代替.
試試看:
  1. Private Sub CommandButton1_Click()
  2.     Dim x As Integer
  3.     x = 2
  4.     Range("E3:I3") = 0
  5.     Do While Cells(x, 1) <> ""
  6.         If Cells(x, 4) = "新" Then
  7.             [I3] = [I3] + Cells(x, 2).Value
  8.         End If
  9.         If Cells(x, 3) = "大" Then
  10.             [F3] = [F3] + Cells(x, 2).Value
  11.         End If
  12.         If Cells(x, 1) = "紅" Or Cells(x, 1) = "紅紅" Then
  13.             [E3] = [E3] + Cells(x, 2).Value
  14.         ElseIf Cells(x, 1) = "綠" Then
  15.             [F3] = [F3] + Cells(x, 2).Value
  16.         ElseIf Cells(x, 1) = "藍" Then
  17.             [G3] = [G3] + Cells(x, 2).Value
  18.         ElseIf Cells(x, 1) = "黃" Then
  19.             [H3] = [H3] + Cells(x, 2).Value
  20.         End If
  21.         x = x + 1
  22.     Loop
  23. End Sub
複製代碼

TOP

        靜思自在 : 有心就有福,有願就有力,自造福田,自得福緣。
返回列表 上一主題