简体   繁体   English

VBA代码仅应用最后一个数据标签

[英]VBA code to apply only the last data label

I don't speak English very well, but I hope you can understand me. 我不会说英语,但我希望你能理解我。

It's about a VBA code for plotting graphs. 它是关于用于绘制图形的VBA代码。 I am trying to automate my sheets and I found a simple and easy code in the internet to do so. 我正在尝试自动化我的工作表,我在互联网上找到了一个简单易用的代码。 After updating the series, my intention is to clear all data labels except for the last one. 更新系列后,我的目的是清除除最后一个之外的所有数据标签。

The code is: 代码是:

Dim oChart As ChartObject
Dim MySeries As Series

For Each oChart In ActiveSheet.ChartObjects
 For Each MySeries In oChart.Chart.SeriesCollection

    'Clear Existing Data Labels
       MySeries.ApplyDataLabels (xlDataLabelsShowNone)

    'Apply Labels to Last Point
        MySeries.points(MySeries.points.Count).ApplyDataLabels

    Next MySeries
Next oChart

End Sub

But, this code runs for only three of the ten graphs, and doesn't work for the others. 但是,此代码仅运行十个图中的三个,而不适用于其他图。 I 've looked for similarities or differences among the series (like the name format or type of graphic - line, bar, pie) but I could not find the problem 我已经找到了系列之间的相似之处或不同之处(比如名称格式或图形的类型 - 线条,条形图,饼图),但我找不到问题

The first part of the macro wich is delete all data labels works correctly for all the graphs, though. 宏的第一部分是删除所有数据标签对所有图形都正常工作。 I also try to do it for more than one sheet and workbook, also unsuccessfully. 我也尝试为多个工作表和工作簿执行此操作,但也未成功。

You should over every-sheet, every chart, every series and points. 你应该超过每张纸,每张图表,每个系列和点。 ApplyDataLabels is a property a point not series or multiple points. ApplyDataLabels是一个属性,不是一个点或多个点。 xlDataLabelsShowNone Doesn't mean none of the points. xlDataLabelsShowNone并不代表任何一点。 It means that the label will not be shown in any format. 这意味着标签不会以任何格式显示。 You can read about this Object here . 你可以在这里阅读这个对象。

Code below would do the job for you. 下面的代码可以帮到你。

Sub remove_label()

    Dim wsh As Worksheet
    Dim oChart As ChartObject
    Dim MySeries As Series
    Dim oPoints As Points
    Dim MyPoint As Point
    Dim i As Long

     For Each wsh In ThisWorkbook.Worksheets
       For Each oChart In wsh.ChartObjects
         For Each MySeries In oChart.Chart.SeriesCollection
           Set oPoints = MySeries.Points
             i = oPoints.Count
                For Each MyPoint In oPoints
                  i = i - 1
                    If i <> 0 Then
                     'Clear Existing Data Labels
                      MyPoint.ApplyDataLabels xlDataLabelsShowNone
                    Else
                     'Apply Labels to Last Point
                      MyPoint.ApplyDataLabels xlDataLabelsShowValue
                    End If

           Next MyPoint
         Next MySeries
       Next oChart
     Next wsh

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM