I am getting an error for my code “Runtime error 4

2019-07-27 16:55发布

My code is working fine but it ends up giving me a runtime error "object required.

I am not able to find out what is causing this error. This code is related to deleting graphs that don't have any data in them .

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

标签: excel vba
2条回答
时光不老,我们不散
2楼-- · 2019-07-27 17:38

An outdated pivotcache and some still remembered but in the meantime missed items caused some trouble to me in the past. So I propose to add this code once before:

Dim pc As PivotCache
For Each pc In ThisWorkbook.PivotCaches
    pc.MissingItemsLimit = xlMissingItemsNone
    pc.Refresh
Next pc
查看更多
姐就是有狂的资本
3楼-- · 2019-07-27 17:52

Change the object passed to the function from Chart to full ChartObjectlike this:

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
查看更多
登录 后发表回答