Change chart axis range programmatically
This article demonstrates a macro that changes y-axis range programmatically, this can be useful if you are working with stock charts and you are not happy with the axis range Excel has chosen for you.
The macro automates this for you, the formulas in cell E2 and E3 extracts the largest and smallest stock price respectively. The macro simply uses those values to change the y-axis range for you, you don't need to change these values manually each time you change the data source (stock ticker).
What you will learn in this article
- Extract the largest and smallest number from a cell range.
- Round a number up and down to the nearest integer.
- Create named range that expands based on size of the data source.
- Change chart axis range programmatically.
- How to use the minimumScale and maximumScale property
- Assign a macro to a chart allowing the user to press with left mouse button on the chart in order to run the macro.
Formula in cell E2:
High is a named range that expands based on the size of the data source, it references the column that contains the highest stock price for a given period.
The MAX function returns the maximum number and the ROUNDUP function rounds the number up to the nearest integer.
Formula in cell E3:
Low is a named range that expands based on the size of the data source, it references the column that contains the lowest stock price for a given period.
The MIN function returns the minimum number and the ROUNDDOWN function rounds that number down to the nearest integer.
How to use named ranges?
- Press with mouse on tab "Formulas" on the ribbon.
- Press with mouse on "Name Manager".
- Press with mouse on "New" button.
- Type the name and paste the formula shown below to "Refers to:".
- Repeat steps with remaining named ranges.
Named range formulas
Close:
Date:
High:
Low:
You can find an explation to these formulas here: Create a dynamic named range
How to use macro?
The macro is rund when you press with left mouse button on the chart, see animated image above. The macro uses the values in cell E2 and E3, the chart axis max and min values are instantly changed.
I also created a dynamic named ranges. You don´t need to adjust chart cell ranges manually anymore when stock data changes.
VBA macro
'Name macro Sub RefreshChart() 'The With ... End With statement allows you to write shorter code by referring to an object only once instead of using it with each property. 'The Axis object has one argument, choose between xlCategory, xlSeriesAxis, or xlValue With Worksheets("Sheet3").ChartObjects("Chart 1").Chart.Axes(xlValue) 'Change maximum scale for chart 1 on sheet 3 to value in cell E2 on worksheet Sheet3 .MaximumScale = Worksheets("Sheet3").Range("E2") 'Change minimum scale for chart 1 on sheet 3 to value in cell E3 on worksheet Sheet3 .MinimumScale = Worksheets("Sheet3").Range("E3") End With End Sub
How to assign macro to the chart
- Press with right mouse button on on a chart.
- Press with left mouse button on on "Assign Macro...".
- Press with mouse on the macro you want to link to the chart.
- Press with left mouse button on OK button.
User defined function
Edit: Yahoo Finance has changed, the following UDF is not working anymore.
You can copy historical stock data from the Yahoo Finance website.
I posted a userdefined function a year ago that automatically imported stock prices from yahoo finance. The workbook demonstrated in this blog posts imports stock prices and refreshes a stock chart. The problem is how excel calculates maximum and minimum axis values.
I made some small modifications to the user defined function.
Stock data are now sorted from smallest to largest by datePrices are numbers
Function YahooStockQuotes(Fyear As String, Fmonth As String, Fday As String _ , Tyear As String, Tmonth As String, Tday As String, interval As String _ , ticker As String) Dim url As String, http As Object Dim csv As String, temp() As Variant, txt As String Dim r As Integer, a As Single, b As String, c As Single, irows As Single Dim temp1() As Variant ReDim temp(6, 0) ReDim temp1(6, 0) url = "https://ichart.finance.yahoo.com/table.csv?s=" & ticker & _ "&d=" & Tmonth - 1 & "&e=" & Tday & "&f=" & Tyear _ & "&d=d&a=" & Fmonth - 1 & "&b=" & Fday & "&c=" & Fyear & "&g=" & interval & "&ignore=.csv" On Error Resume Next Set http = CreateObject("MSXML2.XMLHTTP") http.Open "GET", url, False http.Send csv = http.responseText r = 0 txt = "" For a = 1 To Len(csv) b = Mid(csv, a, 1) If b = "," Then If UBound(temp, 2) = 0 Then temp(r, UBound(temp, 2)) = txt ElseIf r = 0 Then temp(r, UBound(temp, 2)) = txt Else temp(r, UBound(temp, 2)) = Val(txt) End If r = r + 1 txt = "" ElseIf b = Chr(10) Then If UBound(temp, 2) = 0 Then temp(r, UBound(temp, 2)) = txt ElseIf r = 0 Then temp(r, UBound(temp, 2)) = txt Else temp(r, UBound(temp, 2)) = Val(txt) End If ReDim Preserve temp(UBound(temp, 1), UBound(temp, 2) + 1) txt = "" r = 0 Else txt = txt & b End If Next a For c = LBound(temp, 1) To UBound(temp, 1) temp1(c, UBound(temp1, 2)) = temp(c, 0) Next c ReDim Preserve temp(UBound(temp, 1), UBound(temp, 2) - 1) ReDim Preserve temp1(UBound(temp1, 1), UBound(temp1, 2) + 1) For a = UBound(temp, 2) To LBound(temp, 2) Step -1 For c = LBound(temp, 1) To UBound(temp, 1) temp1(c, UBound(temp1, 2)) = temp(c, a) Next c ReDim Preserve temp1(UBound(temp1, 1), UBound(temp1, 2) + 1) Next a irows = Range(Application.Caller.Address).Rows.Count For a = UBound(temp1, 2) - 1 To irows For c = 0 To 6 temp1(c, a) = "" Next c ReDim Preserve temp1(UBound(temp1, 1), UBound(temp1, 2) + 1) Next a YahooStockQuotes = Application.Transpose(temp1) Set http = Nothing End Function
Sheet 2 - Import stock prices
Array formula in cell range C1:I150
Built-in Charts
Combo Charts
Combined stacked area and a clustered column chartCombined chart – Column and Line on secondary axis
Combined Column and Line chart
Chart elements
Chart basics
How to create a dynamic chartRearrange data source in order to create a dynamic chart
Use slicers to quickly filter chart data
Four ways to resize a chart
How to align chart with cell grid
Group chart categories
Excel charts tips and tricks
Custom charts
How to build an arrow chartAdvanced Excel Chart Techniques
How to graph an equation
Build a comparison table/chart
Heat map yearly calendar
Advanced Gantt Chart Template
Sparklines
Win/Loss Column LineHighlight chart elements
Highlight a column in a stacked column chart no vbaHighlight a group of chart bars
Highlight a data series in a line chart
Highlight a data series in a chart
Highlight a bar in a chart
Interactive charts
How to filter chart dataHover with mouse cursor to change stock in a candlestick chart
How to build an interactive map in Excel
Highlight group of values in an x y scatter chart programmatically
Use drop down lists and named ranges to filter chart values
How to use mouse hover on a worksheet [VBA]
How to create an interactive Excel chart
Change chart series by clicking on data [VBA]
Change chart data range using a Drop Down List [VBA]
How to create a dynamic chart
Animate
Line chart Excel Bar Chart Excel chartAdvanced charts
Custom data labels in a chartHow to improve your Excel Chart
Label line chart series
How to position month and year between chart tick marks
How to add horizontal line to chart
Add pictures to a chart axis
How to color chart bars based on their values
Excel chart problem: Hard to read series values
Build a stock chart with two series
Change chart axis range programmatically
Change column/bar color in charts
Hide specific columns programmatically
Dynamic stock chart
How to replace columns with pictures in a column chart
Color chart columns based on cell color
Heat map using pictures
Dynamic Gantt charts
Stock charts
Build a stock chart with two seriesDynamic stock chart
Change chart axis range programmatically
How to create a stock chart
Excel categories
6 Responses to “Change chart axis range programmatically”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
Contact Oscar
You can contact me through this contact form
Works great!! Thanks! As an advice to the people that find this, the chart name is *not* the title of the chart, it is "Chart 1" or "Chart 2", etc. I dunno how to change this.
scasbyte,
As an advice to the people that find this, the chart name is *not* the title of the chart, it is "Chart 1" or "Chart 2", etc.
1. Select a a chart
2. The name box displays the chart name
The chart title is not the chart name.
Hello Oscar, I noticed for the vba code for the chart max and min to change, you have code in Module1 and module 2.
Oscar, Why do you have vba code for the chart max min code in both module 1 and module 2?
Oscar, I noticed I have to press with left mouse button on the chart for the y axis on the chart to change.
Is it possible to automatically change the the y axis, when I change the company symbol? In other words, with out selecting the chart?
Also is there a way where I can add to the drop down list to automatically update as I add more companies and the symbols?
Thanks,
Rene
Rene,
Oscar, Why do you have vba code for the chart max min code in both module 1 and module 2?
You can delete module 2 if you want.
Oscar, I noticed I have to press with left mouse button on the chart for the y axis on the chart to change.
Yes, you need to press with left mouse button on the chart to refresh.
Is it possible to automatically change the the y axis, when I change the company symbol? In other words, with out selecting the chart?
Probably, I have not figured out how yet.
Also is there a way where I can add to the drop down list to automatically update as I add more companies and the symbols?
Yes, create a dynamic named range:
https://www.get-digital-help.com/2011/04/28/create-a-dynamic-named-range-in-excel/
In VBA, I prefer transferring the Y value to an array, and then sorting them low to high (or high to low). Use a bubble sort for that. You can then use the min and max value in the array as the min an max Y values of the chart object. Round up or down if you prefer.
¿Qué tipos de cambio harías en el código, si tu gráfica se te presenta como hoja excel, es decir mueves tu gráfica a ocupar totalmente una nueva hoja excel?
Gracias por tu aporte.