excel 这是否可以以任何方式实现,我有3行以下金额-5,3,2,我需要找到偏移量并定位0金额

57hvy0tb  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(158)

Excel冠军!
这是否可以以任何方式实现,我在A列中有一个值列表,包括负数和正数。如果一组连续的行的总数为0,我想在这些行的B列中放置一个0。对于任何不能这样分组的值,请将B列留空。
假设,我有3行,金额分别为-5,3,2。我需要找到偏移量并定位它们,然后在下一列中放置零。主要目标是找到总计为零的金额。它可以是-2,-2,-1,5 = 0或-1,-3,2,2 = 0
就像下面的例子。

ztyzrc3y

ztyzrc3y1#

这将在两种颜色之间交替。数字列表应在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
dwbf0jvd

dwbf0jvd2#

假设值的总和总是为零,你可以使用SCAN来获得一个累积和,MAP来获得start(零之后的第一个值,或者数组中的第一个值)和end数组中的所有零:

=LET(c, SCAN(   0, A2:A13,
        LAMBDA( x, y,
                x+y)),
     MAP(    c, VSTACK(0, DROP(c,-1)),
     LAMBDA( x, y,
             IF(y=0,
                "start",
                IF(x=0,
                   "end",
                   "")))))

如果你想要一个计数器:

=LET(c,SCAN(   0, A2:A13,
       LAMBDA( x, y,
               x+y)),
     SCAN(   0, VSTACK(0,DROP(c,-1)),
     LAMBDA( x, y,
             x+(y=0))))

相关问题