excel - 在圆环图上定位标签

标签 excel vba excel-2016 excel-charts

我有以下代码尝试将数据标签添加到组合圆环/饼图中的某个点:

    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

如您所见,我已经在图表之外为不同的系列放置了一个标签,该系列表示为饼图。虽然我尝试添加标签的系列表示为圆环图。

我不能在外面同时有 donut 和饼图的标签吗?不是xlLabelPositionOutsideEnd圆环图标签的有效位置?还是问题是我无法解决的其他问题?

任何帮助将不胜感激!

最佳答案

我认为不可能完全按照你想做的方式去做!将标签放置在图表外部的选项在圆环图选项中不可用:

Missing options on doughnut chart

就像他们在饼图上做的那样:

Label position options on a pie chart

但是,您可以通过执行以下操作使用饼图和白色圆圈执行技巧,使其看起来像 donut :

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

有一些有趣的“解决”这个......

关于excel - 在圆环图上定位标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55019356/

相关文章:

excel - 如何使用 Sub 填充(动态)数组的值

vba - 使用 VBA 更改 Excel 表单标签长度以匹配其文本的长度

vba - 无法获取数据透视项目类的可见属性

sql - 无法使用 ADO 从 VBA/Excel 写入 SQL

VBA 错误处理不适用于 Excel 2016 中的一位用户

excel - Excel 2016 for Mac 中的自动调整注释框大小

php - 如何查询列名中带句点的Excel工作表

Excel公式根据条件选择数据范围

带有 SAP GUI 7.40 的 Excel VBA - SAP.Functions 不起作用

excel - 从网站复制 Excel VBA 代码时出现意外的语法错误