我遇到的问题是使用VBA(Excel)中的shapes对象制作的饼图中嵌入了空白图例条目(等于活动工作表的非空行数)。
首先,我不知道为什么会发生这种情况,当我尝试使用co.chart.legend.legendentries(i).delete删除这些不必要的条目时,却显示错误。以下代码是主要代码的一部分。excel screenshot
Sub test()
Dim i,t,m As Integer
Dim wb As Workbook
Dim ws As Worksheet
Dim co As Shape
Set wb = ThisWorkbook
t = 2
m = 2
i = 11
For Each co In activeSheet.Shapes
co.Delete
Next co
Set ws = Sheets("TimeSheet")
ws.Select
Set co = ws.Shapes.AddChart2
With co
.chart.ChartType = xl3DPie
.chart.ChartStyle = 264
.chart.ChartArea.Format.Fill.ForeColor.SchemeColor = 1
.chart.ChartGroups(1).FirstSliceAngle = 90
.chart.SeriesCollection.NewSeries
.chart.SeriesCollection(1).Values = ws.Range(Cells(i,3),Cells(i,5))
.chart.SeriesCollection(1).XValues = ws.Range(Cells(1,Cells(1,5))
.chart.SeriesCollection(1).HasDataLabels = True
.chart.SeriesCollection(1).DataLabels.Position = xlLabelPositionBestFit
.chart.SeriesCollection(1).DataLabels.ShowPercentage = True
.chart.SeriesCollection(1).DataLabels.ShowValue = True
.chart.SeriesCollection(1).HasLeaderLines = True
.chart.SeriesCollection(1).LeaderLines.Border.ColorIndex = 1
.chart.HasTitle = True
.chart.ChartTitle.Text = ("Team " & Cells(m,1))
.chart.HasLegend = True
.Left = Range(Cells(t,7),Cells(t,7)).Left
.Height = Range(Cells(t,Cells(t + 7,7)).Height
.Width = Range(Cells(t,9)).Width
.Top = Range(Cells(t,7)).Top
End With
t = t + 9
m = i + 1
last = co.chart.SeriesCollection(1).Points.count
Data = co.chart.SeriesCollection(1).Values
For g = 1 To last
If Data(g) = 0 Then
co.chart.SeriesCollection(1).Points(g).DataLabel.Delete
End If
Next
End Sub