关于图表:数据标签VBA Excel

Datalabels VBA Excel

我希望有人可以帮助我进行Excel VBA数据标签查询。

在Excel 2016中,我想基于一系列单元格(而不是值)向折线图添加数据标签。范围是一个表列。

出于某种原因,宏运行时没有错误,但是由于范围未被捕获,因此数据标签不显示,即,一旦运行,为数据标签选择的范围仍为空白。

请注意,我已将副本粘贴到相关部分的下方。完整代码中还有更多的系列集合。但是,我仅将标签添加到特定标签。

谢谢蚂蚁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Dim created_table_object As ListObject
Dim created_table As String
Set created_table_object = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$26"), , xlNo)
created_table = created_table_object.Name

Dim waterfall_chart As Chart
Set waterfall_chart = ActiveSheet.Shapes.AddChart2(XlChartType:=xlColumnStacked).Chart

With waterfall_chart
    With .FullSeriesCollection(7)
        .Name ="Positive Data Labels"
        .Values = ActiveSheet.ListObjects(created_table).ListColumns(11).DataBodyRange
        .ChartType = xlLine
        .Format.Line.Visible = msoFalse
        .HasDataLabels = True
        With .DataLabels
            .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange,"ActiveSheet.ListObjects(created_table).ListColumns(12).DataBodyRange", 0
            .Format.TextFrame2.TextRange.Font.Size = 12
            .Format.TextFrame2.TextRange.Font.Bold = msoTrue
            .ShowRange = True
            .ShowValue = False
            .NumberFormat = number_format
            .Position = xlLabelPositionAbove
        End With
    End With
End With


据我所确定,您将需要一个带有.Format.TextFrame2.TextRange.InsertChartField行单元格地址的字符串公式。也许尝试:

1
2
3
.Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, _
   "='" & ActiveSheet.Name &"'!" & _
    ActiveSheet.ListObjects(created_table).ListColumns(12).DataBodyRange.Address, 0

"='" & ActiveSheet.Name &"'!"为范围的字符串地址获取所需的工作表名称,并带有所需的等号,因为公式是必需的。

您还可以声明一个字符串变量,然后在格式行中使用它来帮助代码更清晰地阅读:

1
2
3
    Mystr ="='" & ActiveSheet.Name &"'!" & ActiveSheet.ListObjects(created_table).ListColumns(12).DataBodyRange.Address

   .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, Mystr, 0