找到下一个空白单元格和autosum

时间:2016-09-30 03:37:21

标签: excel-vba vba excel

我在连续范围内的多列中有相同月份的数据。

每个月份范围由空白列分隔。

我想要的是一个宏,它在列起始单元格B10中找到下一个空白单元格,并自动清空空白单元格之前的列。

我想在黄色突出显示的列中使用autosum(必须是循环)。

sample image

我开始编写代码但卡住了:

Sub sum()

    ActiveSheet.Range("b10").Select

    Selection.Columns.End(xlToRight).Offset(0, 1).Select

    ActiveCell.Value = "=Sum(columns.end (xltoleft)"

End Sub

非常感谢 索菲亚

1 个答案:

答案 0 :(得分:0)

变量

  • x:跟踪当前行
  • y:要汇总的范围中的第一列
  • y1:要求和的范围中的最后一列

enter image description here

Sub AddColumnSums()

    Dim x As Long, y As Long, y1 As Long
    For x = 10 To Range("A" & Rows.Count).End(xlUp).Row
        If Cells(x, 1).Value <> "" Then
            y = 2 ' Initialize the start column
            Do
                ' xlToRight brings you to the last cell in a continous cell block
                y1 = Cells(x, y).End(xlToRight).Column

                ' The formula is assigned the first cell after continous cell block

                Cells(x, y1 + 1).Formula = "=Sum(" & Range(Cells(x, y), Cells(x, y1)).Address & ")"

                'The starting column is set to the first cell after the formula
                y = y1 + 2

            ' If there is no more data to the right of the starting column
            ' xlToRight will reference the last cell in the row and 
            ' the column loop will eixt

            Loop Until Cells(x, y).End(xlToRight).Column = Columns.Count
        End If
        'Increments to the next row
    Next
End Sub