Quantcast
Channel: Excel & VBA - Databison » interactive chart

5 easy ways to make data validation work for you

0
0

One of the easiest ways to add interactivity to your spreadsheets and dashboard is to use the data validation feature in excel. Data validation allows you specify a list of options that you want a cell to display as a drop-down.

You may want to download the sample sheet here before we begin.

To being creating a dropdown for a particular cell, select the cell and click Data -> Validation. In the validation criteria dropdown box, choose “List”. Remember – you can specify both static values (1,2,3,4) or named ranges (=listoffruits, if you have one defined already)

Static values: Type in the values seperated by commas (Ex. Roberto, Wilhelm, Akido) in the “Source” box. Click Ok and check the list that appears in the cell dropdown.
Named ranges: Excel provides you with a feature to set a name for a continous range of cells. These are what are referred to as “Named Ranges”. Enter values Pizza, Hamburger, Noodles in three seperate but continous cells. Now select all the three cells. In the Name Box (usually situated right above the left intersection of row and column headers) type “food”. Now we can go back to Data -> Validation and select “List” in the drop-down. In the “Source” field enter =food and click ok. You will see a dropdown with the values of the cells you named as “food”.

What’s more you can make these named ranges dynamic such that depending on some criteria a name may refer to a certain selelction of cells at some points and a different selection of cells at other. Well this can be done by *managing* the list – a list that does not explicitly refer to a fixed grouping of cells but rather to a group of cells returned by a formula. The excel “OFFSET” formula is my personal favourite. Usually offset() allows return the value of a cell which is certain number of rows and columns away from a cell. However, further arguments can be specified that can return a range of cells that is not only a certain number of rows and columns away from a cell but also a cells high and b cells across. Example =offset($a$1,1,2, 4,5) will return a range of cells whose first cells is C2 and the last cell is H6. If we reduce the value 4 OR the value 5 in above example (which specify the number of rows and columns of the range to be returned) to 1, we will get a linear (horizontal OR vertical) array of cells. If we could put this formula as the range for a named range point to, we’ve just made for ourselves a Dynamic Named Range.

Click on Insert -> Name -> Define. Enter a descriptive name in the “Names in workbook” field and in the “Refers to” box, ente the above formula as =offset($a$1, 1, 2, 1, 4). Ensure that The cells C2 to H2 have some names in them. Click ok. You will now see a dropdown against that particular cell. You can further modify the value of the value 4 and replace it with some formula (=count(NumberOfPeople) or something of this nature) so that the number of values in the dropdown of you cell now becomes dependent upon some user input and is can therefore change on the fly !!!


6 Easy Steps to Making an Interactive Map Chart in Excel

0
0

Creating interactive map charts in excel is one of the easiest things to do…..that is if you know how. I recently created this map chart showing the top 50 tropical storms to hit the Unitef States since 1900. As you move ahead in time from 1900 to 2005, the map shows the states that were hit by the storm, the damage caused, storm category and rank. It takes about 5 lines of code per map unit (in this case a state) to render this effect.

You can download the file here.

Steps to create this interactive chart map in excel:
1. Get relevent data and lay it out clearly.

2. Prepare a placeholder for the map and the information points (Dates, Names, $’s etc.)

3. Introduce a dynamic control (in this case a horizontal scrollbar) that the user can use to interact with the graphic.


4. Insert formulae and charts so that when the user moves the dynamic conrtol, values get updated.

5. Inroduce the map chart (in this case the WMF map of the U.S.)

6. Write VBA code to make the relevent map objects behave in accordance with the user inputs.


(Data taken from Report by Pielke, Gratz, Landsea, Collins, Saunders and Musulin )

Stock Chart with Scroll and Zoom

0
0

Stock charts come in various shapes. There are candlestick stock charts, line and bar stock charts, “Kagi” stock charts, moving average stock charts and everything in between. For a financial service provider how to present financial information pertaining to a specific stock can a critical question. On one hand, if you give too many options, you loose out on user comfort and increase API complexity. On the other, give too few options and you end up losing more demanding customers. Interesting to note is that both Yahoo and Google tend to use the same type of stock chart displays though personally I tend to use the former.

stock-chart-as-shown-in-yahoo-finance

This stock chart has the ability to scroll across historical share price data and yet allows the user to zoom into any specific portion that may need to be studied with greater detail. This is something that would’ve taken me more than a few page refreshes to achieve using a conventional stock chart (something that is still used by a number of financial service providers even today). And that got me thinking, is there a way to make a stock chart in excel that has both these abilities. The good news is that I was able to get pretty close to creating a similar looking stock chart with scroll and zoom.

stock-chart-with-scroll-and-zoom

The stock chart above that has two controls – the first one allows to you move across a timeline and view changes in share price and volume over the complete time horizon. The second control allows you to control the amount of data you see in the chart. You can move the slider and compress or expand the time duration for which data is shown in a single frame. The obvious advantage of using this type of a chart is that rather than having a large number of smaller charts to study the stock’s behavior over a period of time, you can use a single chart to view the entire available data in one go and narrow down into specific portions the stock chart that warrant closer scrutiny.

To create a stock chart in Excel with scroll and zoom functionality, follow these steps:

1. Place the data required for the stock chart (stock price and volume in our case) in an excel spreadsheet. Ensure that the data is clean and free from errors. While placing the data in the excel spreadsheet, ensure that the successive data elements are placed in adjacent columns. Although it is not a mandatory step, it will help the data layout look neat and help debug formulae without errors.

2. Create another blank range which is of the same width and height as the original data set (in point 1).

3. Now in the first cell of the new range (range2) , use the OFFSET function to offset the corresponding cell in original data set by X number of rows (hint use =OFFET(original_cell, X_rows_to_offset, 0)). Copy this formula to all cells in the range such that each cell in range2 is offset by the same number of rows. Now, the exact number of rows to offset (represented by X) will be controlled by a particular cell. You can use any cell in the spreadsheet for that purpose such that it does not interfere with the chart data. Replace X_rows_to_offset in the above formula with the address of the cell that controls the offset. In step 9 we will get to make this cell change its value dynamically by attaching this to a scroll bar.

4. Create a chart in the spreadsheet using ‘Insert’ -> ‘Chart’ option from the menu.

insert-the-stock-chart

5. Format the chart as per your needs (you can use bar charts, line charts, box plots or any other chart type that serves your purpose and the available data.)

6. Enable the Forms Toolbar by clicking ‘View’ -> ‘Toolbars’ -> ’Forms’ from the menu.

7. Important – Click anywhere on the chart window. From the Forms Toolbar, select the scrollbar icon. Now draw a neat little scrollbar within the chart area.

8. Double click the scrollbar and in the ‘Controls’ tab choose the ‘Cell Link’ box. Select the cell we choose the cell that controls the offset value of the cells in range2 (refer step 3). Provide the minimum value as 1 and the maximum value as the count of the number of rows that you have in your original data set.

scroll-bar-control

9. Now press Esc a couple of times. Your stock chart should be nearly ready at this point. Simple play around with the scrollbar, drag it around and you will see that the chart scrolls along the x-axis. If nothing happens, check through all the previous points especially 3 and 8.

10. Once you have the scroll functionality working on the stock chart, its time to add the functionality to stretch the graph. The ability to stretch or collapse a time frame allows the user to narrow down or broaden the amount of historical stock price data that he/she gets to see at one go. It can be useful to quickly identify points of interest and then analyze them in greater detail.

11. To add the stretch-collapse functionality to the stock chart, repeat step 7 to add another scrollbar within the chart.

12. For the second scrollbar, repeat step 9. Select the linked cell as a new cell adjacent to the one linked to the first scrollbar. The minimum and maximum values should be somewhere between 7 and the number of days for which you’d like to see the data together.

13. Now comes the tricky part. To ensure that our data points in the stock chart expand/contract as per the user needs, we will have to delete the earlier data series and create a dynamic named range that stretches and contracts dynamically.

14. Create a new named range using “insert’ -> ‘Name’ -> ‘Define’ from the menu. In the Define Name box, enter the following formula (=OFFET(original_cell, 0, 0, Y_rows_to_offset, 0)). This is a slightly different variation of the OFFSET function which lets you expand or contract a range by a certain amount of rows or columns. (See named range for more on this topic). You will have to create as many of these named ranges as the number of data series you want to show on your chart (plus one for the label). The ‘original_cell’ here is the first cell of each of the corresponding data series (first cell of each column of range2) in the worksheet.

15. Right click on the stock chart and choose ‘Source data’. For each of the data series, edit the source data by replacing the source range reference with the name of the corresponding dynamic named ranges that you created in step 14. (Caution – If the named range does not result in a valid range, this will cause problems)

16. Click ok. Now play around with the second scrollbar and you should see the stock chart stretch or expand as you drag it with the mouse. If it does not, go through steps 11 to 15 again.

If you followed all these steps closely, you would have observed that we did not use VBA code anywhere in this example although I may add, that the results was as good looking as the Google stock chart.

Interactive Chart in VBA using Mouse Move Event

0
0

VBA can be used to make interactive charts that respond to mouse movements. In this article we first start of by making a simple bar chart embedded in a chart sheet and then use the mouse move event of the chart sheet to make it interactive.

Create a simple Bar Chart

For the purpose of this exercise, we take the list of top 15 billionaires and sort it based on their networth.

data-for-interactive-chart-vba

We then create a simple bar chart using the networth as the pot values and the names as X-Axis lables. The last step in the creation of this bar chart is when excel prompts you for the location at which the new chart is to be placed. We select the chart to be placed in a new sheet.

insert-chart-as-new-sheet

The application will then place a special sheet which acts as a placeholder for the chart. The important thing to nore here is that this sheet (called the “chart sheet”) exposes certain functions such as the mouse move, mousedown, mouseup etc) that the generally not available to a chart embedded in a normal excel worksheet.

Once the chart has been created, we remove all the chartjunk and provide proper labels.
chart-in-a-chart-sheet

Adding VBA code to make the Chart Interactive

A chart sheet exposes the mousemove event which can be exploited to know the position of the pointer at any given point in time. The coordinates of the mouse pointer are provided inherently as X and Y variables. We then pass on these variables to the chart’s GetChartElement function. This function helps provide details of what chart elements exist at a given X and Y coordinate. The syntax of the GetChartElement function is as follows:

ChartObject.GetChartElement(X, Y, ElementID, Arg1, Arg2)

where :
ChartObject refers to the chart whose
X The X coordinate of the chart element.
Y The Y coordinate of the chart element.
ElementID This argument returns the XLChartItem value of the chart element at the specified coordinate.
Arg1 and Arg2 Additional arguments that provide details related to the chart object

(The me keyword serves pretty much the function as this in java – it helps get a handle on the current object.)

Please bear in mind that ElementID, Arg1 and Arg2 are passed byRef which means that their values get changes as a result of being specified as arguments to the method. So in essence, we provide only the first two arguments with the remaining three being returned with fresh values by the method.

Here is screenshot from MS VBA help file that shows that those return values for the ElementID, Arg1 and Arg2 indicate.

elementid-of-a-chart-in-vba-interactive-chart

We now check the ElementID to see if the underlying element is an xlSeries – indicating that the mouse is over an data plot series – a bar in a bar chart or a line in a line chart. Once we know that the underlying element is a data plot, all that needs to be done to make the chart interactive is the fill in the code with the steps we would like to take. In our case, we simply provide the mouse pointer with a tool tip that comes up when the mouse moves over a bar and disappears when it moves out of the bar. While at it, we add another effect – which is to make that particular bar “light-up” when the mouse moves over it.

The final effect is that whenever the mouse moves over a bar in our interactive chart, a tool-tip appears with customized description and the bar changes color.

interactive-chart-vba

The code to achieve this entire effect has been give below. The original code developed by Jon Peltier can be found here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Private Sub Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, ByVal x As Long, ByVal y As Long)
Dim ElementID As Long
Dim Arg1 As Long
Dim Arg2 As Long
Dim chart_data As Variant
Dim chart_label As Variant
Dim last_bar As Long
Dim chrt As Chart
Dim ser As Series

On Error Resume Next

Me.GetChartElement x, y, ElementID, Arg1, Arg2

Set chrt = ActiveChart
Set ser = ActiveChart.SeriesCollection(1)
chart_data = ser.Values
chart_label = ser.XValues

Set txtbox = ActiveSheet.Shapes("hover")

If ElementID = xlSeries Then
    If Err.Number Then
        Set txtbox = ActiveSheet.Shapes.AddTextbox _
                                        (msoTextOrientationHorizontal, x - 150, y - 150, 100, 100)
        txtbox.Name = "hover"
        txtbox.Fill.Solid
        txtbox.Fill.ForeColor.SchemeColor = 9
        txtbox.Line.DashStyle = msoLineSolid
        chrt.Shapes("hover").TextFrame.Characters.Text = "$ " & Application.WorksheetFunction.Text(chart_data(Arg2), "???.??") & " bn" & Chr(10) & Chr(10) & chart_label(Arg2)
        With chrt.Shapes("hover").TextFrame.Characters.Font
            .Name = "Arial"
            .Size = 12
            .ColorIndex = 16
        End With
        With chrt.Shapes("hover").TextFrame.Characters(Start:=1, Length:=11).Font
            .Name = "Haettenschweiler"
            .Size = 20
            .ColorIndex = 1
        End With
        last_bar = Arg2
    End If
    ser.Points(Arg2).Interior.ColorIndex = 44
    txtbox.Left = x - 150
    txtbox.Top = y - 150
   
Else
    txtbox.Delete
    ser.Interior.ColorIndex = 16
End If
End Sub

You can download a sample worksheet with the interactive chart using VBA mouse move event here or click on the button below:

interactive chart using VBA mouse move event





Latest Images