Excel:将标签添加到XY图表中的数据点

我想要在Excel图表中的数据点旁边添加标签。 有一个来自Microsoft的VBA代码用于此目的:

http://support2.microsoft.com/kb/914813/en-us

Sub AttachLabelsToPoints() 'Dimension variables. Dim Counter As Integer, ChartName As String, xVals As String ' Disable screen updating while the subroutine is run. Application.ScreenUpdating = False 'Store the formula for the first series in "xVals". xVals = ActiveChart.SeriesCollection(1).Formula 'Extract the range for the data from xVals. xVals = Mid(xVals, InStr(InStr(xVals, ","), xVals, _ Mid(Left(xVals, InStr(xVals, "!") - 1), 9))) xVals = Left(xVals, InStr(InStr(xVals, "!"), xVals, ",") - 1) Do While Left(xVals, 1) = "," xVals = Mid(xVals, 2) Loop 'Attach a label to each data point in the chart. For Counter = 1 To Range(xVals).Cells.Count ActiveChart.SeriesCollection(1).Points(Counter).HasDataLabel = _ True ActiveChart.SeriesCollection(1).Points(Counter).DataLabel.Text = _ Range(xVals).Cells(Counter, 1).Offset(0, -1).Value Next Counter End Sub 

它到目前为止工作。 但是,只有collections品没有名字:

在这里输入图像说明

当我命名集合然后macros返回一个错误:

在这里输入图像说明

有谁知道如何使用Mircosoft提供的代码,仍然能够命名数据收集?

我有同样的问题。 所有你需要做的是用'InStr(xVals,“,”)'replace硬编码的'9',它将在第一个逗号之前的字段中接受任何长度的序列名。

在图表生成之后(假设图表在同一张表中)试试这个:(根据您的需要修改)

 Option Explicit Sub RenameChartDataLabel() Dim rngDLabel As Range Dim iii as integer, pp as integer, dlcount as integer Set rngDLabel = ActiveSheet.Range("A2:A6") 'change range for datalabels text ActiveSheet.ChartObjects("Chart 2").Activate 'change chart name dlcount = ActiveChart.SeriesCollection(1).DataLabels.Count iii = 1 pp = 1 For iii = dlcount To 1 Step -1 ActiveChart.SeriesCollection(1).DataLabels(iii).Select Selection.Text = rngDLabel(pp).Value Selection.Font.Bold = True Selection.Position = xlLabelPositionAbove pp = pp + 1 Next Set rngDLabel = Nothing End Sub 

在这里输入图像说明