Excel图表VBA循环通过数据标签

时间:2017-01-31 14:17:36

标签: excel vba excel-vba excel-2010 excel-charts

我有很多表格上都有图表,我想循环遍历每个图表中的每个数据标签,删除任何等于0,但似乎无法提取数据标签值。

With ActiveChart
    For k = 1 To .SeriesCollection.Count
        For j = 1 To .SeriesCollection(k).Points.Count
            For l = 1 To .SeriesCollection(k).Points(j).DataLabels.Count
               If .SeriesCollection.Points(j).DataLabels(l) = 0 Then
                   .SeriesCollection.Points(j).DataLabel(l).Delete
                End If
            Next l
        Next j
    Next k
End With

(忽略每个图表的循环,激活每个图表,该位有效,因此保持代码示例最小)

有人可以建议如何循环数据标签,检查值,并在适当的地方删除吗?

1 个答案:

答案 0 :(得分:4)

你很亲密!

您只错过.Caption来检查DataLabel内的文字价值!

我将DataLabels(l)更改为DataLabels.Item(l)(您的代码中存在异常)。

With ActiveChart
    For k = 1 To .SeriesCollection.Count
        For j = 1 To .SeriesCollection(k).Points.Count
            For l = 1 To .SeriesCollection(k).Points(j).DataLabels.Count
               If .SeriesCollection.Points(j).DataLabels.Item(l).Caption = 0 Then
                   .SeriesCollection.Points(j).DataLabels.Item(l).Delete
                End If
            Next l
        Next j
    Next k
End With

OP使用的最终代码:

With ActiveChart
    For k = 1 To .SeriesCollection.Count
        For j = 1 To .SeriesCollection(k).Points.Count
            If .SeriesCollection(k).Points(j).DataLabel.Caption = 0 Then
                .SeriesCollection(k).Points(j).DataLabel.Delete
           End If
        Next j
    Next k
End With