0

请看下面的代码:

Sub CreatePieCharts()

'Declare the variables

    Dim wks As Worksheet
    Dim AddtionalCharts As Chart
    Dim MySeries As Series
    Dim Rng As Range
    Dim CatRange As Range
    Dim SourceRange As Range
    Dim SourceData As Range
    Dim LeftPos As Double
    Dim TopPos As Double
    Dim Gap As Integer
    Dim i As Long
    Dim j As Long
    Dim k As Long

    'Set the range for the source data from the active worksheet
    Set Rng = Range("A1").CurrentRegion

    'Set the position of the first chart
    LeftPos = Range("M3").Left
    TopPos = Range("M3").Top

    'Set the gap between charts
    Gap = 5

    'Set the range for the category values
    For j = 1 To Rng.Columns.Count
        For i = 2 To Rng.Columns.Count

            If j Mod 2 = 1 And i Mod 2 = 0 Then _
                Set SourceData = Union(Rng.Columns(j), Rng.Columns(i))

            'Create the pie charts

            Set AddtionalCharts = ActiveSheet.Shapes.AddChart.Chart
            With AddtionalCharts
                .SetSourceData SourceData, xlColumns
                .ChartType = xlPie
                .ApplyDataLabels xlDataLabelsShowValue, False
                .Parent.Left = LeftPos
                .Parent.Top = TopPos
                TopPos = TopPos + .Parent.Height + Gap
            End With
        Next i
    Next j

End Sub

基本上,宏需要遍历列并根据列的偶数或奇数状态创建图表。例如:Chart1 和 Answer 1 应该是一张图表,Chart2 和 Answer2 应该是下一张,依此类推。

现在我可以创建图表,但由于某种原因,还有一些其他额外的图表显示我不需要。我究竟做错了什么?

4

1 回答 1

0

我认为您只需要将饼图创建位包含到您的If构造中。现在不是,所以无论如何都会创建一个图表。

你在做什么是这样的:

If <condition> Then <statement1>

<statement2>

在这里,<statement2>无论<condition>.

改为这样做:

If <condition> Then
    <statement1>
    <statement2>
    '...
End If

在这种情况下,<statement2>只有在满足时才会被执行(连同<statement1><condition>

在您的具体情况下:

            If j Mod 2 = 1 And i Mod 2 = 0 Then
                Set SourceData = Union(Rng.Columns(j), Rng.Columns(i))
                'Create the pie charts
                Set AddtionalCharts = ActiveSheet.Shapes.AddChart.Chart
                With AddtionalCharts
                    .SetSourceData SourceData, xlColumns
                    .ChartType = xlPie
                    .ApplyDataLabels xlDataLabelsShowValue, False
                    .Parent.Left = LeftPos
                    .Parent.Top = TopPos
                    TopPos = TopPos + .Parent.Height + Gap
                End With
            End If
于 2013-11-13T07:44:47.230 回答