LegendEntries,Range,PieChart,Delete,Condition

时间:2016-06-15 23:30:15

标签: vba range conditional-statements legend pie-chart

我一直在试图找出错误或者我做错了几天。我在这里显示当前的输出和它应该是什么。我想也许我正在定义范围有一些错误,或者LegendEntries(i)可能与Points(i)使用相同的索引。有什么建议吗?或者也许我怎么能用另一种方法做到这一点?

这里的目的是获取图表并删除与“0”值相关联的图例和标签。

第一张图是我当前的输出。 第二个是我的愿望输出,以及我希望用我的代码得到的东西。

具有0值的传说是“亚洲”和“拉特”,但我当前的输出是抛出“Latam”并且它应该抛出“RoW”,因为“RoW”与0值无关,它的值是“5.0%”。

Sub CreateChart()
On Error Resume Next
Sheets(1).ChartObjects.Delete

    Dim MyChart As Chart
    Dim rowi As Integer
    Dim MyRange As Range


rowi = Range("I7").Row ' Index to select last row non empty, in this example it's row number 11.
Do While Sheets(1).Cells(rowi, Range("I7").Column).Value = _
IsEmpty(Cells(rowi, Range("I7").Column))
rowi = rowi + 1
Loop

'----------------------------------------------------CHART---------------------------------------------------------------

Set MyRange = Range("I6:M6" & ",I" & rowi & ":M" & rowi)

Set MyChart = Sheets(1).Shapes.AddChart(xlPie).Chart

     MyChart.SetSourceData Source:=MyRange

With MyChart.SeriesCollection(1)
 .HasDataLabels = True
 .DataLabels.NumberFormat = "0.0%"
End With

With MyChart
 .HasLegend = True
End With

For i = 1 To (Range("M6").Column - Range("I6").Column + 1)

If  Cells(rowi, Range("I6").Column + i - 1).Value = 0 Then
MyChart.SeriesCollection(1).Points(i).DataLabel.Delete
MyChart.Legend.LegendEntries(i).Delete
End If

Next i
End Sub

Current Output

Desire Output

1 个答案:

答案 0 :(得分:2)

托帕斯,你走了。您遇到的问题是,每次从LegendEntries对象中删除其中一个图例条目时,其余条目的索引编号都会向下移动1以填充该孔。因此,在删除索引3(亚洲)后,索引4变为3,5,变为4,依此类推......为了解决问题,我只是在索引号中倒退,从而确保删除不会影响事物的顺序来吧。

 Sub CreateChart()
    On Error Resume Next
    Sheets(1).ChartObjects.Delete
        Dim MyChart As Chart
        Dim rowi As Integer
        Dim MyRange As Range
    rowi = Range("I7").Row ' Index to select last row non empty, in this example it's row number 11.
    Do While Sheets(1).Cells(rowi, Range("I7").Column).Value = _
        IsEmpty(Cells(rowi, Range("I7").Column))
        rowi = rowi + 1
    Loop

    '----------------------------------------------------CHART---------------------------------------------------------------

    Set MyRange = Range("I6:M6" & ",I" & rowi & ":M" & rowi)

    Set MyChart = Sheets(1).Shapes.AddChart(xlPie).Chart
         MyChart.SetSourceData Source:=MyRange

    With MyChart.SeriesCollection(1)
     .HasDataLabels = True
     .DataLabels.NumberFormat = "0.0%"
    End With
    MyChart.HasLegend = True

    For i = (Range("M6").Column - Range("I6").Column + 1) To 1 Step -1 ' <---CHANGED THIS
        If Cells(rowi, Range("I6").Column + i - 1).Value = 0 Then
            MyChart.SeriesCollection(1).Points(i).DataLabel.Delete
            MyChart.Legend.LegendEntries(i).Delete
        End If
    Next i
End Sub

希望这有帮助,如果您有任何疑问,请随时询问。