Avoiding the use of Activate and Select when working with charts (Excel)

蓝咒 提交于 2020-01-03 14:22:07

问题


I know that using Activate and Select in Excel VBA is not best practice. I've seen references on how to avoid them when dealing with Ranges (example: LINK). How can I avoid them when dealing with ChartObjects (or anything other than Ranges, in general)?

For instance, a way to modify the maximum value on the y-axis using Activate and Select would look something like this (which works):

        ActiveSheet.ChartObjects("MyChart").Activate
        ActiveChart.Axes(xlValue).Select
        ActiveChart.Axes(xlValue).MaximumScale = Range("MaxVal").Value

In order to avoid using Activate and Select, I tired to declare variables, and work with those, but that does not work:

     Dim ws As Worksheet
     Set ws = Worksheets("Chart")
     With ws.ChartObjects("MyChart").Axes(xlValue)
        .MaximumScale = Range("MaxVal").Value
     End With

The code above runs (i.e. does not throw an error), but the scale on the axis does not change. What am I missing?


EDIT: Got it to work with this "longwinded" version:

    With Worksheets("Chart").ChartObjects("MyChart").Chart.Axes(xlValue)
        .MaximumScale = Range("MaxVal").Value
    End With

回答1:


As for your question #1: How can I avoid them when dealing with ChartObjects (or anything other than Ranges, in general)?, the method you use is correct. Your conclusion that does not work is brought about by the other error.

As for your question #2: What am I missing?, a ChartObject does not have a method Axes. What you called the "longwinded" version is actually the way to do it.

PS: The only reason I can think about for the non-working code to run with no error is an error handler that ignores the error. I get the expected "Run-time error '438': Object doesn't support this property or method".




回答2:


This finally worked:

        With Worksheets("Chart").ChartObjects("MyChart").Chart.Axes(xlValue)
            .MaximumScale = Range("MaxVal").Value
        End With


来源:https://stackoverflow.com/questions/20479409/avoiding-the-use-of-activate-and-select-when-working-with-charts-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!