在VBA中编码多行图形(循环)

时间:2018-08-22 21:56:14

标签: excel vba loops

我敢肯定,这个问题的答案很简单,但是我已经花了好几天的时间试图弄清楚这个问题,而且我所在部门中没有人与VBA合作。 我是自动化图表的新手,但我有一个项目需要制作近800张图表!数据本身非常简单,具有4个变量(列):县,城市,商店类型和员工人数:

COUNTY  CITY    STORE TYPE  NUMBER OF EMPLOYEES
X   A   1   100
X   A   2   100
X   A   3   100
X   A   4   100
X   B   1   100
X   B   2   100
X   B   3   100
X   B   4   100

我需要为每个县/市组合制作条形图,其中商店类型为X值,Y轴上显示的员工人数。这在VBA中非常容易做到:

Sub makegraph2()
Range("A2:D5").Select
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$2:$D$5")
ActiveChart.ChartTitle.Text = "Employees per Store Type"
Selection.Format.TextFrame2.TextRange.Characters.Text = "Employees per Store 
Type"
End Sub

我不是在复制/粘贴相同的图形并向下向下每4行重新选择数据,而是在尝试找到一种自动执行循环的方法。我已经尝试过自己进行此操作(仅用50行进行测试((A2:D50代表所有4列和50行)),以免出现800个错误的图形并使计算机崩溃的情况)以多种不同方式使用偏移量。我最讨厌的尝试是一次生成一个包含所有50行的图形:

Sub makegraph()
Dim Row As Integer

For Row = 1 To 50
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!A2:D50").Offset(4, 0)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "Employees by Store Type"
Next Row
End Sub

在此之前,我制作了单独的图形,但是它们都是相同的数据(不会下降4行以绘制下一组图形)。所以很明显我在使用Offset和Range时出错,但是我不知道如何...

任何帮助都非常感谢!!谢谢!!

2 个答案:

答案 0 :(得分:2)

未经测试,但请尝试以下操作:

Sub makegraph()

    Dim i As Long, co, cht As Chart '<<edit here
    Dim sht As Worksheet

    Set sht = Sheets("Sheet1")

    For i = 1 To 50
        Set co = ActiveSheet.Shapes.AddChart2(201, xlColumnClustered)
        'position and size the chart here by setting the
        '  Top/Left/Width/Height properties
        With co.Chart
            'calculate the required offset
            .SetSourceData Source:=sht.Range("A2:D5").Offset((i - 1) * 4, 0)
            .ChartTitle.Text = "Employees by Store Type"
        End With
    Next i
End Sub

答案 1 :(得分:1)

Sub makegraph()
Dim Row As Integer

For Row = 1 To 50
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!A2:D50").Offset(4, 0)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "Employees by Store Type"
Next Row
End Sub
根据我对这段代码的了解。您应用的偏移量始终与Range(“ Sheet!A2:D50”)所在的位置相同。其次,您已将整个区域指定为源。

我建议做更多的绝对值或为该范围变量:

可变范围示例:

Sub makegraph()
    Dim Row As Integer
    Dim Area As Range

    Set Area = Range("A2:D5")

    For Row = 1 To 50
        ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
        ActiveChart.SetSourceData Source:=Area
        Set Area = Area.Offset(4, 0)
        ActiveChart.ChartTitle.Select
        ActiveChart.ChartTitle.Text = "Employees by Store Type"
    Next Row
End Sub

绝对值示例:

Sub makegraph()
    Dim Row As Integer

    For Row = 2 To 50 Step 4
        ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
        ActiveChart.SetSourceData Source:=Range(Cells(Row, 1), Cells(Row + 3, 1))
        ActiveChart.ChartTitle.Select
        ActiveChart.ChartTitle.Text = "Employees by Store Type"
    Next Row
End Sub