我的代码“运行时错误424”出现错误

时间:2019-01-18 11:42:35

标签: excel vba

我的代码运行正常,但最终却给我一个运行时错误“需要对象。

我无法找出导致此错误的原因。此代码与删除其中没有任何数据的图有关。

Sub HideEmptyCharts()
    Dim wksCharts As Worksheet
    Dim objCO As ChartObject

    ' Set up a variable for the worksheet containing the charts
    Set wksCharts = ThisWorkbook.Sheets("Report output")

    ' Loop through every embedded chart object on the worksheet
    For Each objCO In wksCharts.ChartObjects
        ' Make each one visible
        objCO.Visible = True

        ' If the chart is empty make it not visible
        If IsChartEmpty(objCO.Chart) Then objCO.Visible = False
    Next objCO
End Sub

Private Function IsChartEmpty(chtAnalyse As Chart) As Boolean
    Dim i As Integer
    Dim j As Integer
    Dim objSeries As Series

    ' Loop through all series of data within the chart
    For i = 1 To chtAnalyse.SeriesCollection.Count
        Set objSeries = chtAnalyse.SeriesCollection(i)

        ' Loop through each value of the series
        For j = 1 To UBound(objSeries.Values)
            ' If we have a non-zero value then the chart is not deemed to be empty
            If objSeries.Values(j) <> 0 Then
                ' Set return value and quit function
                IsChartEmpty = False
                Exit Function
            End If
        Next j
    Next i

    IsChartEmpty = True
End Function

error image

2 个答案:

答案 0 :(得分:0)

过时的数据透视缓存,有些仍然被记住,但与此同时,遗漏的项目过去给我带来了麻烦。因此,我建议将此代码添加一次:

Dim pc As PivotCache
For Each pc In ThisWorkbook.PivotCaches
    pc.MissingItemsLimit = xlMissingItemsNone
    pc.Refresh
Next pc

答案 1 :(得分:0)

将传递给函数的对象从Chart更改为完整的ChartObject,如下所示:

Private Sub HideEmptyCharts()
    Dim wksCharts As Worksheet
    Dim objCO As ChartObject

    Set wksCharts= ThisWorkbook.Sheets("Report output")
    For Each objCO In wksCharts.ChartObjects
        objCO.Visible = True
        If IsChartEmpty(objCO) Then objCO.Visible = False
    Next objCO
End Sub


Private Function IsChartEmpty(co As ChartObject) As Boolean
    Dim i As Integer
    Dim j As Integer
    Dim objSeries As Series
    For i = 1 To co.Chart.SeriesCollection.Count
        Set objSeries = co.Chart.SeriesCollection(i)
        For j = 1 To UBound(objSeries.Values)
            If objSeries.Values(j) <> 0 Then
                IsChartEmpty = False
                Exit Function
            End If
        Next j
    Next i
    IsChartEmpty = True
End Function