How do I reference charts with the same name, but on different worksheets?

后端 未结 3 682
渐次进展
渐次进展 2021-01-04 10:32

I have two worksheets containing charts, and use a macro to run over all the sheets with charts in them and update the values charted.

However, I run into a problem

3条回答
  •  伪装坚强ぢ
    2021-01-04 11:03

    As you've discovered, the Workheet.ChartObjects method will find the correct ChartObject, but accessing the Chartobject.Chart property will return the Chart of the ActiveSheet. It doesn't matter if you refer to the ChartObject by name or by Index number.

    The behavior is the same if you use the Worksheet.Shapes method to find the ChartObject.

    This behavior is different to earlier versions of Excel. I confirmed that the code worked in Excel XP/2002, and doesn't work in 2016. I'm unsure when the behavior changed. It might have been 2013, or it might have been a patch to 2013 and 2016? The behavior in Office for mac 2016 is the same (ie. doesn't work)

    Until Microsoft comes up with a fix, you'll have to activate the sheet, or activate the ChartObject, before you access the Chart property.

    Sub test()
      Dim ws As Worksheet
      Dim co As ChartObject
      For Each ws In ThisWorkbook.Worksheets
        Debug.Print ws.Name
        Set co = ws.ChartObjects("Kortsone")
    
        ws.Activate
        'or
        co.Activate
    
        Debug.Print co.Chart.Name
        With ws.ChartObjects("Kortsone").Chart
        End With
      Next ws
    End Sub
    

    I suggest that you temporarily disable ScreenUpdating, and reactivate the originally activesheet once you're done.

提交回复
热议问题