在甜甜圈图中放置标签

时间:2019-03-06 09:13:03

标签: excel vba excel-2016 excel-charts

我有以下代码尝试将datalabel添加到组合的甜甜圈/饼图中的点:

    For Each co In .ChartObjects
        With co.Chart.FullSeriesCollection("Grøn pil").Points(2)
            .HasDataLabel = True
            With .DataLabel
                .Position = xlLabelPositionOutsideEnd
                .Format.AutoShapeType = msoShapeRectangle
                .Format.Line.Visible = msoTrue
            End With
        End With
    Next co

但是,代码在行.Position = xlLabelPositionOutsideEnd中中止,并显示错误消息“运行时错误2147467259(80004005)”。对象'DataLabel'的方法'Position'失败”。

查看图表,标签已添加,但仍位于图表内部。

enter image description here

如您所见,我已经在图表之外的其他系列中放置了一个标签,该标签以饼图的形式表示。在尝试添加标签的系列时,它以甜甜圈图表示。

外面不能同时有甜甜圈图和饼图的标签吗? xlLabelPositionOutsideEnd是否不是甜甜圈标签标签的有效位置?还是这个问题让我难以理解?

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

我认为不可能完全按照自己的意愿去做!将标签放置在图表外部的选项在甜甜圈图表选项上不可用:

Missing options on doughnut chart

就像在饼图上一样:

Label position options on a pie chart

但是,您可以执行以下操作,使用饼图和白色圆圈使它看起来像甜甜圈:

Sub AddCircle()
    'Get chart size and position:
        Dim CH01 As Chart: Set CH01 = ThisWorkbook.Sheets("Sheet1").ChartObjects("Chart1").Chart
        Dim OB01 As ChartObject: Set OB01 = CH01.Parent
        Dim x As Double: x = 0 'horizontal coordinate
        Dim y As Double: y = 0 'vertical coordinate
        Dim w As Double: w = 0 'width
        Dim h As Double: h = 0 'height
        x = OB01.Left
        y = OB01.Top
        w = OB01.Width
        h = OB01.Height
    'Adding the circle:
        ThisWorkbook.Sheets("Sheet1").Shapes.AddShape(msoShapeOval, x + w / 2 - 20, y + h / 2 - 20, 40, 40).Name = "Circle01"
    'Formatting the circle:
        With ThisWorkbook.Sheets("Sheet1").Shapes("Circle01")
            .LINE.Visible = msoFalse
            .Fill.ForeColor.RGB = RGB(255, 255, 255)
        End With
End Sub

它非常好用:

Pie chart with a hole

“解决”这个问题很有趣...

答案 1 :(得分:0)

使用窦和余弦,我们还可以计算标签的外侧位置。按照VB代码段,该如何完成:

Sub Macro1()
    Dim cx
    Dim cy
    Dim x
    Dim y
    Dim radius
    Dim angle
    Dim new_radius
    Dim new_x
    Dim new_y

    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveSheet.ChartObjects("Chart 1").Select
    cx = Selection.width / 2
    cy = Selection.height / 2

    For i = 1 To ActiveChart.FullSeriesCollection(1).Points.Count Step 1
        ActiveChart.FullSeriesCollection(1).Points(i).DataLabel.Select
        x = Selection.left + (Selection.width / 2)
        y = Selection.top + (Selection.height / 2)
        radius = Sqr(((x - cx) ^ 2) + ((y - cy) ^ 2))
        angle = WorksheetFunction.Atan2(y - cy, x - cx)
        new_radius = radius + 40
        new_x = cx + (Sin(angle) * new_radius)
        new_y = cy + (Cos(angle) * new_radius)
        Selection.left = new_x - (Selection.width / 2)
        Selection.top = new_y - (Selection.height / 2)
    Next i
End Sub
相关问题