2016-11-18 1 views
1

"A"という変数に正の値を追加するExcelマクロを作成しようとしています。それが負に変化したら、すべての負の値を "B"に加えます。再度正に変化したら、すべての値を「C」に加えます。それが再び負になると、すべての負を "D"に追加します。例えば複数の変数に入るまで合計を設定するマクロアーキテクチャ

私のデータがある場合: Data-> (0,0,1,-1,1,1,-1,-1,0,0,-1) 私はそれについて移動する方法がわからないよ出力が

A=1 
B=-1 
C=2 
D=-3 

になりたいです。

答えて

1

あなたは配列の値を持っていると仮定すると、それはあなたが切り替える必要がある場合を決定するために、現在の符号を追跡するだけの単純な問題だ:

Private Sub DemoCode() 
    Dim values() As Variant 
    values = Array(0, 0, 1, -1, 1, 1, -1, -1, 0, 0, -1) 

    Dim sign As Long, i As Long 
    Dim current As Long, results As New Collection 
    sign = 1 
    For i = LBound(values) To UBound(values) 
     '0 is "signless". 
     If values(i) <> 0 Then 
      'Did the sign change? 
      If values(i) \ Abs(values(i)) <> sign Then 
       'Store the accumulated result. 
       results.Add current 
       'Flip the sentinel sign. 
       sign = -sign 
       'Reset the accumulator. 
       current = 0 
      End If 
     End If 
     current = current + values(i) 
    Next I 
    'Add the last result. 
    results.Add current 

    Dim result As Variant 
    For Each result In results 
     Debug.Print result 
    Next 
End Sub 
関連する問題