我正在尝试创建一个excel宏,它将积极的值添加到变量“A”中。当它变为负数时,将所有负值添加到“B”中。当它再次变为正值时,将所有值添加到“C”中。当它再次变为负数时,将所有负数添加到“D”......依此类推。
例如,如果我的数据是:
Data-> (0,0,1,-1,1,1,-1,-1,0,0,-1)
我希望输出
A=1
B=-1
C=2
D=-3
我不确定如何去做。
答案 0 :(得分: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