Sunday, June 23, 2019
Avoiding the use of Activate and Select when working with charts (Excel)
Answer
Answer
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
Answer
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".
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
When the left part is an object instance, you use -> . Otherwise, you use :: . This means that -> is mostly used to access instance m...
-
I've been asked to update some Excel 2003 macros, but the VBA projects are password protected, and it seems there's a lack of docume...
-
I got a stupid problem with SQL that I can't fix. ALTER TABLE `news` ADD `dateAdded` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AUTO...
No comments:
Post a Comment