对所有工作表重复一个宏

时间:2018-10-01 12:43:35

标签: excel-vba

Sub Format()

Dim LastRow As Long

Columns("A:E").Select
Range("A3").Activate
Columns("A:E").EntireColumn.AutoFit
Rows("7:7").Select
Selection.Delete Shift:=xlUp
Range("B16").Select

LastRow = Range("D9").End(xlDown).Row
Cells(LastRow + 1, "D").Formula = "=SUM(D9:D" & LastRow & ")"

End Sub

我正在处理需要向具有相同结构的不同数量数据表的个人进行报告的工作表。如果我需要为所有工作表重复代码,该怎么办。我是stackoverflow的追随者,并从该论坛中学到了很多东西。

谢谢 克沙夫

1 个答案:

答案 0 :(得分:0)

循环浏览

Sub Format()

    Dim LastRow As Long, sh As Worksheet

    For Each sh In Sheets
        With sh
            .Columns("A:E").EntireColumn.AutoFit
            .Rows("7:7").Delete Shift:=xlUp
            LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
            .Cells(LastRow + 1, "D").Formula = "=SUM(D9:D" & LastRow & ")"
        End With
    Next sh
End Sub

除一张纸外循环浏览

Sub LoopSheetsExceptOne()
    Dim LastRow As Long, sh As Worksheet, ws As Worksheet

    Set ws = Sheets(1)

    For Each sh In Sheets

        If sh.Name <> ws.Name Then

            With sh
                .Columns("A:E").EntireColumn.AutoFit
                .Rows("7:7").Delete Shift:=xlUp
                LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
                .Cells(LastRow + 1, "D").Formula = "=SUM(D9:D" & LastRow & ")"
            End With

        End If

    Next sh

End Sub