循环通过工作表的宏

时间:2014-03-05 14:59:24

标签: excel vba excel-vba excel-2007

下面的宏执行计算并生成条形图。目前它适用于第一个工作表(Sheet1),我希望能够在我的Excel工作簿中的所有工作表上重复相同的宏。有一个简单的方法吗?提前谢谢。

Sub MyReport()
     Workbooks.Open Filename:= _
        Application.GetOpenFilename
    Range("G2").Select
    ActiveCell.FormulaR1C1 = "=SUM(C[-5])"
    Range("H2").Select
    ActiveCell.FormulaR1C1 = "=SUM(C[-5])"
    Range("I2").Select
    ActiveCell.FormulaR1C1 = "=SUM(C[-5])"
    Range("J2").Select
    ActiveCell.FormulaR1C1 = "=SUM(RC[-3]:RC[-1])"
    Range("G1:I2").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("'Sheet1'!$G$1:$I$2")
    ActiveChart.ChartType = xlColumnStacked
End Sub

1 个答案:

答案 0 :(得分:3)

以下是如何使用a for each循环将代码应用于每个工作表。我还简化了一些代码。

Sub MyReport()
    Dim Wkb As Workbook
    Dim Ws As Worksheet
    Dim chrt As Chart

    Set Wbk = Workbooks.Open(Filename:=Application.GetOpenFilename)

    For Each Ws In Wbk.Worksheets
        Ws.Range("G2:I2").FormulaR1C1 = "=SUM(C[-5])"
        Ws.Range("J2").FormulaR1C1 = "=SUM(RC[-3]:RC[-1])"

        Set chrt = Ws.Shapes.AddChart.Chart
        chrt.SetSourceData Source:=Ws.Range("$G$1:$I$2")
        chrt.ChartType = xlColumnStacked
    Next Ws
End Sub

结果(显示表1):

enter image description here