在Excel VBA中将所有上述求和到下一个空白单元格之前汇总到空白单元格中

时间:2017-12-22 12:26:51

标签: excel vba excel-vba excel-formula spreadsheet

我已经获得了这个电子表格,我需要总结工作时间。 在专栏' I'我已经完成了所有工作时间,我按行周排序排序' E'通过以下循环,我在谷歌的某个地方找到了(不记得是谁编写了它但它有效)。

Dim i, itotalrows As Integer
Dim strRange As String

itotalrows = ActiveSheet.Range("E20000").End(xlUp).Offset(1, 0).Row


Do While i <= itotalrows
    i = i + 1
    strRange = "E" & i
    strRange2 = "E" & i + 1
    If Range(strRange).Text <> Range(strRange2).Text Then
        Rows(i + 1).Insert
        itotalrows = ActiveSheet.Range("E20000").End(xlUp).Offset(1, 0).Row
        i = i + 1
    End If

Loop

在图片中,您可以看到一个标有&#34的单元格;单元格的总值 &#34; 每隔几行都有一个空格,上面有一个单元格&#39;我&#39;总值应该去哪里。

图纸图片:

enter image description here

3 个答案:

答案 0 :(得分:1)

也许根据第G列中的空白位置对第I列中的组进行求和。

Sub x()

Dim r As Range

For Each r In Range("G:G").SpecialCells(xlCellTypeConstants).Areas
    r.Cells(r.Count + 1).Offset(, 2).Value = WorksheetFunction.Sum(r.Offset(, 2))
Next r

End Sub

答案 1 :(得分:0)

如果您要使用以下内容替换代码,我相信它应该符合您的期望:

Sub foo()
Dim i, itotalrows As Integer
Dim strRange As String

itotalrows = ActiveSheet.Range("E20000").End(xlUp).Offset(1, 0).Row

Do While i <= itotalrows
    i = i + 1
    strRange = "E" & i
    strRange2 = "E" & i + 1
    If Range(strRange).Text <> Range(strRange2).Text Then
        Rows(i + 1).Insert
        Cells(i + 1, "I").FormulaR1C1 = "=SUMIF(C[-4],R[-1]C[-4],C)"
        'when inserting a new row, simply add this formula to add up the values on column I
        itotalrows = ActiveSheet.Range("E20000").End(xlUp).Offset(1, 0).Row
        i = i + 1
    End If
Loop
End Sub

看到您的代码已经按照您想要的那样(即,当列E上的值不同时添加新行),然后将该公式添加到该行中将在列I上添加任何内容,其中列E的值相同。

答案 2 :(得分:0)

这是如何对空白单元格中的单元格求和的一般方法。 如果这是输入,那么正确的ppicture应该是输出:

enter image description hereenter image description here

使用此代码:

Sub TestMe()    
    Dim myCell      As Range
    Dim currentSum  As Double        
    For Each myCell In Worksheets(1).Range("A1:A14")
        If myCell = vbNullString Then
            myCell = currentSum
            myCell.Interior.Color = vbRed
            currentSum = 0
        Else
            currentSum = currentSum + myCell
        End If
    Next myCell           
End Sub

这个想法只是为currentSum使用一个变量,并在每次单元格为空时写入它。如果它不为空,则使用单元格值

递增它