Being beginner and first time on this site, I truly appreciate your help.

WK 1    WK 2    WK 3    WK 4    WK 5    TOTAL HOURS TOTAL OF FIRST 3 WEEKS <> 0

John 10 0 5 6 5 26 21

Smith 4 1 10 3 4 22 15

Peter 0 4 4 4 2 14 12

Susan 5 5 0 5 8 23 15

SO23257561 example

From my table I want to add only the first three columns that contain no zero. If there's zero on first three, check on next column and add it up to complete three columns again with no zero value. Some function like in Col H TOTAL OF FIRST 3 WEEKS <>0 (where I had to do it manually).

If I can learn set of VB code or any example with formula or macros, thank you so so much. I'm using Excel 2007.

有帮助吗?

解决方案

This is the complicated formula Ali M refers to. It's an array formula entered with ctrl-shift-enter:

=IF(COUNTIF(A2:F2,"<>0")=0,0,SUM(A2:INDEX(A2:F2,SMALL(IF(A2:F2<>0,COLUMN(A2:F2),""),MIN(3,COUNTIF(A2:F2,"<>0"))))))

Note that it works if there are less than three non-zero values.

其他提示

you can use formula but it would be complicated. instead you can use this subroutine that act exactly as you want!

Public Sub y()
    Dim i, sum, c As Integer

    Dim Rng, Row, cell As Range


    Set Rng = Range("B2:F5")

    i = 0

    For Each Row In Rng.Rows
        For Each cell In Row.Cells
            If (cell.Value <> 0 And i < 3) Then
                sum = sum + cell.Value
                i = i + 1
            End If
        Next cell
        Cells(Row.Row, 7).Value = sum
        sum = 0
        i = 0
    Next Row

 End Sub

It always put the sum in column H. you can change it by changing this line:

Cells(Row.Row, 7).Value = sum
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top