Excel VBA 中 XY 图表的数据标签

Datalabel for XY chart in Excel VBA

我需要修改 vba 上的代码,该代码在 XY 图上进行标记。当样本系列在水平位置共享时,我有一个代码可以很好地工作。但是我有一个系列,它实际上是由两个不同的系列组成的,一个接一个地躺在 table 上。我上图吧,也显示了我的目标。

我使用的当前代码不适用于我的实际情况如下:

 'Name macro
Sub AddDataLabels()
 
'Enable error handling
On Error Resume Next
 
'Display an inputbox and ask the user for a cell range
Set Rng = Application.InputBox(prompt:="Select cells to link" _
, Title:="Select data label values", Default:=ActiveCell.Address, Type:=8)
 
'Disable error handling
On Error GoTo 0
 

With ActiveChart
 
'Iterate through each series in chart
For Each ChSer In .SeriesCollection

    'Save chart point to object SerPo
    Set SerPo = ChSer.Points

    'Save the number of points in chart to variable j
    j = SerPo.Count

    'Iterate though each point in current series
    For i = 1 To j

        'Enable data label for current chart point
        SerPo(i).ApplyDataLabels Type:=xlShowValue

        'Save cell reference to chart point
        SerPo(i).DataLabel.FormulaLocal = Rng.Cells(i).FormulaLocal
        '& rng.Cells(i).Reference(ReferenceStyle:=xlR1C1)
    Next
Next
End With
End Sub

如果我运行上述数据系列的代码,图表将产生如下结果:

那么如何修改这段代码以获得目标图表,请帮助我。

问题是在For循环中,'i'变量只到j,在本例中是3。你需要一个变量来控制标签,这样它就会从1到6(选择标签的范围)。

我创建了一个变量 curLabel,它在 for 循环中使用和递增。这是您要找的吗?

Sub AddDataLabels()
    Dim curLabel As Integer: curLabel = 1
    
    'Enable error handling
    On Error Resume Next
     
    'Display an inputbox and ask the user for a cell range
    Set Rng = Application.InputBox(prompt:="Select cells to link" _
        , Title:="Select data label values", Default:=ActiveCell.Address, Type:=8)
        
    'Disable error handling
    On Error GoTo 0

    With ActiveChart
            
        'Iterate through each series in chart
        For Each ChSer In .SeriesCollection

            'Save chart point to object SerPo
            Set SerPo = ChSer.Points

            'Save the number of points in chart to variable j
            j = SerPo.Count

            'Iterate though each point in current series
            For i = 1 To j

                'Enable data label for current chart point
                SerPo(i).ApplyDataLabels Type:=xlShowValue

                'Save cell reference to chart point
                SerPo(i).DataLabel.FormulaLocal = Rng.Cells(curLabel).FormulaLocal
                '& rng.Cells(i).Reference(ReferenceStyle:=xlR1C1)
                
                ' Next label
                curLabel = curLabel + 1
            Next
        Next
    End With
End Sub

您可以更改单元格值 'Horizontal Series' 和 'Vertical Series' 并且图例会自动更新,或者您可以像下面的代码一样在其他地方设置图例。

Sub AddCustomLegend()
    Dim myLegend As String
    
    ' series 1 legend
    myLegend = "=" & ActiveSheet.Name & "!" & Range("C12").Address
    ActiveChart.SeriesCollection(1).Name = myLegend

    ' series 2 legend
    myLegend = "=" & ActiveSheet.Name & "!" & Range("D12").Address
    ActiveChart.SeriesCollection(2).Name = myLegend
End Sub