添加到工作簿的每个新工作表的Autosum vba

时间:2018-10-16 15:03:16

标签: excel vba function sum

我当前的VBA为代码中指定和定义的工作表中的预定义列提供求和功能。效果很好,但是我每天都在向该工作簿中添加新的工作表,因此每天编辑代码以添加新的工作表和求和范围是不可行的。

有没有一种方法可以编辑我的当前代码,以便它对工作簿中的每个工作表执行求和功能?我已在下面附加了当前代码以供参考。

    Sub AutoSum()
Sheets("MASTER ACCOUNT REVENUE").Select
Range("D4").Select
Selection.End(xlDown).Select
ActiveCell.Offset(2, 0).Select
Dim cel1 As String, cel2 As String
cel1 = ActiveCell.Offset(-2, 0).End(xlUp).Address
cel2 = ActiveCell.Offset(-1).Address
ActiveCell.Value = "=sum(" & (cel1) & ":" & (cel2) & ")"
End Sub

2 个答案:

答案 0 :(得分:2)

是的,只需遍历工作表即可。注意:它是best to avoid using .Select/.Activate

Sub autoSum_AllSheets()
Dim ws As Worksheet
Dim cel1 As String, cel2 As String
Dim firstCel As Range

For Each ws In ActiveWorkbook.Worksheets
    With ws
        Set firstCel = .Range("D4").End(xlDown).Offset(2, 0)
        cel1 = firstCel.Offset(-2, 0).End(xlUp).Address
        cel2 = firstCel.Offset(-1).Address
        firstCel.Value = "=SUM(" & cel1 & ":" & cel2 & ")"
    End With
Next ws

End Sub

注意:我知道Offset()部分中的冗余,但只是将它们保留在OP中,以了解如何更轻松地避免使用.Select / .Activate

编辑:要遍历一堆列,一种方法(尽管很笨拙)是将列字母添加到数组中:

Sub autoSum_AllSheets()
Dim ws As Worksheet
Dim cel1 As String, cel2 As String
Dim firstCel As Range

Dim cols() As Variant
cols = Array("D", "E", "F")

Dim i As Long
For Each ws In ActiveWorkbook.Worksheets
    With ws
        For i = LBound(cols) To UBound(cols)
            Set firstCel = .Range(cols(i) & "4").End(xlDown).Offset(2, 0)
            firstCel.Select
            cel1 = firstCel.Offset(-2, 0).End(xlUp).Address
            cel2 = firstCel.Offset(-1).Address
            firstCel.Value = "=SUM(" & cel1 & ":" & cel2 & ")"
        Next i
    End With
Next ws

End Sub

不过请注意,如果该列在第5行之后的单元格中没有没有包含任何信息,则会出现错误(因为.XlDown移至最后一行,并且您就不能从那里Offset(2,0)了。)

答案 1 :(得分:0)

是的,请添加

Dim wscount as long
dim i as long
     wscount = Activeworkbook.Worksheets.Count
 for i = 1 to wscount
Sheets(i).Select
Range("D4").Select
 Selection.End(xlDown).Select
ActiveCell.Offset(2, 0).Select
Dim cel1 As String, cel2 As String
cel1 = ActiveCell.Offset(-2, 0).End(xlUp).Address
cel2 = ActiveCell.Offset(-1).Address
ActiveCell.Value = "=sum(" & (cel1) & ":" & (cel2) & ")"
next i 

结束子