返回列表 上一主題 發帖

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

回復 1# wiemanson
  1. Option Explicit
  2. Sub Ex()
  3.     Dim x As Integer, S As Variant, AR(), AC()
  4.     With ActiveSheet
  5.         AC = Array("紅", "綠", "藍", "黃")              '顏色陣列: 指定顏色(0-3),顏色可再增加(0-?)
  6.         AR = Array("E3", "F3", "G3", "H3", "I3")  '顏色位置陣列 (紅,綠,藍,黃,總重量): 儲存格的位置(0-4)
  7.         '總重量位置 :UBound(AR) -> 顏色位置陣列的索引值
  8.         .Range(AR(0) & ":" & AR(UBound(AR))) = ""
  9.         x = 2
  10.         Do While .Cells(x, 1) <> ""
  11.             If .Cells(x, 4) = "新" Then
  12.                 S = UBound(AR)                          '
  13.                 .Range(AR(S)) = .Range(AR(S)) + Cells(x, 2)
  14.             Else
  15.                 S = Mid(.Cells(x, 1), 1, 1)             '如紅紅時可讀取"紅"
  16.                 If .Cells(x, 3) = "大" Then S = "綠"
  17.                 S = Application.Match(S, AC, 0)         'Match 如找不到:傳回錯誤值
  18.                 If IsNumeric(S) Then                    'S: 在指定顏色陣列中的位置
  19.                     .Range(AR(S - 1)) = .Range(AR(S - 1)) + .Cells(x, 2)
  20.                 End If
  21.             End If
  22.             x = x + 1
  23.         Loop
  24.         S = UBound(AR)
  25.         .Range(AR(S)) = .Range(AR(S)) + Application.Sum(.Range(AR(0) & ":" & AR(S - 1)))
  26.     End With
  27. End Sub
複製代碼
  1. Sub aa()
  2.     Dim x As Integer, sum1 As Long, sum2 As Long, sum3 As Long, sum4 As Long, sum5 As Long, sum6 As Long
  3.     x = 2
  4.     sum1 = 0
  5.     sum2 = 0
  6.     sum3 = 0
  7.     sum4 = 0
  8.     sum5 = 0
  9.     Do While Cells(x, 1) <> ""
  10.         If Cells(x, 4) = "新" Then
  11.             sum5 = sum5 + Cells(x, 2).Value
  12.         ElseIf Cells(x, 1) = "紅" Then
  13.             sum1 = sum1 + Cells(x, 2).Value
  14.         ElseIf Cells(x, 1) = "紅紅" Then
  15.             sum1 = sum1 + Cells(x, 2).Value
  16.         ElseIf Cells(x, 1) = "綠" Or Cells(x, 3) = "大" Then
  17.             sum2 = sum2 + Cells(x, 2).Value
  18.         ElseIf Cells(x, 1) = "藍" Then   'Cells(x, 3) !!!
  19.             sum3 = sum3 + Cells(x, 2).Value
  20.         ElseIf Cells(x, 1) = "黃" Then 'Cells(x, 3) !!!
  21.             sum4 = sum4 + Cells(x, 2).Value
  22.         End If
  23.         x = x + 1
  24.     Loop
  25.     Cells(3, 5) = sum1
  26.     Cells(3, 6) = sum2
  27.     Cells(3, 7) = sum3
  28.     Cells(3, 8) = sum4
  29.     Cells(3, 9) = sum5 + sum1 + sum2 + sum3 + sum4
  30. End Sub
複製代碼
感恩的心......(在麻辣家族討論區.用心學習會有進步的)
但資源無限,後援有限,  一天1元的贊助,人人有能力.

TOP

        靜思自在 : 要比誰更受誰.不要比誰更怕誰。
返回列表 上一主題