首页 > 解决方案 > 自定义图表点数据标签位置

问题描述

我正在尝试在 VBA 中设置图表点的 DataLabel,但找不到方法。在这段代码的最后一部分,我设置了图表点的属性,但我不知道如何设置自定义位置,我附上了我想要的结果图片:

objCht.Chart.SetSourceData Source:=ResBook.Sheets(Right(NombreHoja, 2)).Range("P1:R" & UltFilaGrafico)
objCht.Activate
Call AgregarEjeSecundario("Velocidad [km/h]", 3)

ActiveChart.Axes(xlValue, xlSecondary).Select
ActiveChart.Axes(xlValue, xlSecondary).MaximumScale = CInt(TargetVelocity) + 10
ActiveChart.Axes(xlValue, xlSecondary).MinimumScale = 0
ActiveChart.Legend.Position = xlLegendPositionBottom


'ActiveChart.SeriesCollection(2).Points(50).MarkerStyle = xlDiamond
With ActiveChart.SeriesCollection(1)
    '.Points(StopEventRow).MarkerStyle = xlDiamond
    .Points(StopEventRow).MarkerStyle = xlMarkerStyleTriangle
    '.Points(StopEventRow).MarkerSize = 10
    .Points(StopEventRow).MarkerBackgroundColor = RGB(255, 0, 0)    'Rojo
    .Points(StopEventRow).MarkerForegroundColor = RGB(1, 1, 1)

    .Points(StopEventRow).HasDataLabel = True
    .Points(StopEventRow).DataLabel.text = "Detención"
    '.Points(StopEventRow).ApplyDataLabels Type:=xlValue
    .Points(StopEventRow).DataLabel.Font.ColorIndex = 3
    '.Points(StopEventRow).DataLabel.Position = xlLabelPositionCustom
    '.Points(StopEventRow).ApplyDataLabels Type:=xlShowLabel

End With

这就是我试图通过 VBA 代码完成的任务。

在这里我手动设置标签的位置,我试图通过代码来完成

在此处输入图像描述

标签: excelvba

解决方案


这是我使用宏记录器发现的一个基本示例:

Sub AddDataLabel()

    Dim dl As DataLabel, cht As Chart, pt As Point

    Set cht = ActiveSheet.ChartObjects(1).Chart

    Set pt = cht.SeriesCollection(1).Points(6)

    pt.ApplyDataLabels

    Set dl = pt.DataLabel

    With dl
        .Text = "hello"
        .Font.Color = vbRed
        'move label relative to data point
        .Top = pt.Top - 15
        .Left = pt.Left + 15
    End With

End Sub

在此处输入图像描述


推荐阅读