运行时错误'438'循环遍历工作表的每个图表

时间:2017-06-28 20:24:31

标签: excel vba excel-vba

我正在使用宏来浏览工作表的每个图表以隐藏任何带有#N / A值/标题的数据标签(我在图表中使用两个系列,一个绿色和一个红色,具体取决于目标)

当我运行这个sub时,我得到了:“运行时错误'438':对象不支持此属性或方法

发生这种情况的代码行是这样的:
For l = 1 To .SeriesCollection(k).Points(j).DataLabels.Count

我一直关注这个问题的许多其他问题/答案,但是当涉及到这种错误时,每个案例似乎都不同。

是否有人对VBA有更好的理解,可以指出问题所在?

   Sub LoopThroughCharts()
'PURPOSE: Loop through every graph in the a selected worksheet

Dim sht As Worksheet
Dim CurrentSheet As Worksheet
Dim cht As ChartObject

Application.ScreenUpdating = False
Application.EnableEvents = False

Set CurrentSheet = ActiveSheet

With ActiveWorkbook.Worksheets("Graph Annuel")
  For Each cht In .ChartObjects
    cht.Activate
    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 = "#N/A" Then
                   .SeriesCollection.Points(j).DataLabels.Item(l).Delete
                End If
            Next l
        Next j
    Next k
   End With
  Next cht
End With

CurrentSheet.Activate
Application.EnableEvents = True

End Sub

1 个答案:

答案 0 :(得分:2)

您无法对Points(j).DataLabels进行迭代,因为Point对象没有DataLabels属性。

尝试此操作(修改为删除标题只使用空字符串):

Dim cObj As ChartObject, cht As Chart, srs As Series, p As Integer
For Each cObj In ActiveSheet.ChartObjects
    Set cht = cObj.Chart
    With cht
        For Each srs In .SeriesCollection
            If srs.HasDataLabels Then
                For p = 1 To srs.Points.Count
                    If srs.Points(p).HasDataLabel Then
                        If srs.DataLabels.Item(p).Caption = "#N/A" Then
                            srs.DataLabels.Item(p).Caption = ""
                        End If
                    End If
                Next
            End If
        Next
    End With
Next

尝试从集合中删除,除非您在反向索引中执行此操作,否则您将遇到错误(这是可能的,但在这种情况下,当您只能使用空字符串时则不必)。

还添加了一些逻辑,以确保在已删除DataLabel时不会出现错误(即srs.HasDataLabel True可能FalsePoint系列中的个人x_orig = x