Excel冠军!
这是否可以通过任何方式实现,我在 A 列中有一个值列表,包括负值和正值。如果一组连续的行总计为 0,我想在这些行的 B 列中放置一个 0。对于任何不能像这样分组的值,请将 B 列留空。
假设,我有 3 行,数量分别为 -5、3、2。我需要找到偏移量并找到它们并将零放入下一列。主要目的是找到总计为零的金额。它可以 -2,-2,-1,5 = 0 或 -1,-3,2,2 = 0
就像下面的例子。
这将在 2 种颜色之间交替。数字列表应在 A 列中,0 将写在 B 列中。
Sub sum_groups()
Dim CurrentCell As Range, CurrentRange As Range, rg As Range
Dim LastRow As Long
Dim ColorIndex As Long
LastRow = ActiveSheet.UsedRange.Rows.Count
ColorIndex = 6
Set CurrentCell = ActiveSheet.Range("A2")
Set CurrentRange = CurrentCell
'Loop until end of list
Do Until CurrentCell.Row = LastRow
'Loop until 0 group is found
Do Until WorksheetFunction.sum(CurrentRange) = 0
'Break loop if last row is reached
If CurrentCell.Row + CurrentRange.Rows.Count > LastRow Then Exit Do
Set CurrentRange = CurrentRange.Resize(CurrentRange.Rows.Count + 1)
Loop
If WorksheetFunction.sum(CurrentRange) = 0 Then
'Alternate color
If ColorIndex = 6 Then
ColorIndex = 4
ElseIf ColorIndex = 4 Then
ColorIndex = 6
End If
'Enter 0 and change color
For Each rg In CurrentRange
rg.Interior.ColorIndex = ColorIndex
rg.Offset(0, 1) = 0
Next rg
'Move to next cell after current range
Set CurrentCell = CurrentCell.Offset(CurrentRange.Rows.Count)
Else
'Move to next cell after current tested cell
Set CurrentCell = CurrentCell.Offset(1)
End If
'Reset CurrentRange
Set CurrentRange = CurrentCell
Loop
End Sub