<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener("load", function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <iframe src="http://www.blogger.com/navbar.g?targetBlogID=34083602&amp;blogName=LEARN+MS-ACCESS+TIPS+AND+TRICKS&amp;publishMode=PUBLISH_MODE_FTP&amp;navbarType=BLUE&amp;layoutType=CLASSIC&amp;homepageUrl=http%3A%2F%2Fmsaccesstips.com%2F&amp;searchRoot=http%3A%2F%2Fblogsearch.google.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" title="Blogger Navigation and Search"></iframe> <div></div>

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Thursday, July 10, 2008

PIE CHART OBJECT AND VBA

This is the continuation of a discussion on working with Chart Object in VBA. We have created a small Table and a Report with a Chart Object on it, in the earlier Post Working with Chart Object in VBA and gone through few simple Property changes on the Chart Object to get prepared for the Demo of the VBA Programs. Please go through Steps 1 to 7 explained in the earliest Post, by following the link above, and continue.


You may have a look at the Column Chart and VBA topic at your convenience as well.


If you have already tried out the Code given in the earlier Posts then you are familiar with most of the Code Segments that you see here and will have no difficulty in understanding them. The difference is only in the formatting method of individual PIE Slices and few property changes also. In this example we will try three types of Pie Charts: 1. 3D Pie, 2. 3D Pie Exploded, 3. Pie of Pie.


  1. Copy and Paste the Code given below into a Global Module in your Database.


    Public Function PieChart(ByVal ReportName As String, _
    ByVal ChartObjectName As String)
    '---------------------------------------------------
    'Author : a.p.r. pillai
    'URL : http://www.msaccesstips.com
    'Date : July-2008
    'Customized Source Code : from Microsoft Access Help
    '---------------------------------------------------
    Dim Rpt As Report, grphChart As Object
    Dim msg As String, lngType As Long, cr As String
    Dim ctype As String, typ As Integer, j As Integer
    Dim db As Database, rst As Recordset, recSource As String
    Dim colmCount As Integer, chartType(1 To 5) As String
    Const twips As Long = 1440

    On Error GoTo PieChartChart_Err

    chartType(1) = "3D Pie Chart"
    chartType(2) = "3D Pie Exploded"
    chartType(3) = "Pie of Pie"
    chartType(4) = "Quit"
    chartType(5) = "Select 1-4, 5 to Cancel"

    cr = vbCr & vbCr
    msg = ""
    For j = 1 To 5
    msg = msg & j & ". " & chartType(j) & cr
    Next

    ctype = "": typ = 0
    Do While typ < 1 Or typ > 4
    ctype = InputBox(msg, "Select Chart Type")
    If Len(ctype) = 0 Then
    typ = 0
    Else
    typ = Val(ctype)
    End If
    Loop

    Select Case typ
    Case 4
    Exit Function
    Case 1
    lngType = xl3DPie
    Case 2
    lngType = xl3DPieExploded
    Case 3
    lngType = xlPieOfPie
    End Select

    DoCmd.OpenReport ReportName, acViewDesign
    Set Rpt = Reports(ReportName)

    Set grphChart = Rpt(ChartObjectName)

    grphChart.RowSourceType = "Table/Query"
    recSource = grphChart.RowSource

    If Len(recSource) = 0 Then
    MsgBox "RowSource value not set, aborted."
    Exit Function
    End If

    'get number of columns in chart table/Query
    'if Table or SQL string is not valid then
    'generate error and exit program
    Set db = CurrentDb
    Set rst = db.OpenRecordset(recSource)
    colmCount = rst.Fields.Count
    rst.Close

    're-size the Chart
    With grphChart
    .ColumnCount = colmCount
    .SizeMode = 3
    .Left = 0.2917 * twips
    .Top = 0.2708 * twips
    .Width = 5 * twips
    .Height = 4 * twips
    End With

    'activate the chart for modification.
    grphChart.Activate

    'Chart type, Title, Legend, Datalabels,Data Table
    With grphChart
    .chartType = lngType
    .HasLegend = True
    .HasTitle = True
    .ChartTitle.Font.Name = "Verdana"
    .ChartTitle.Font.Size = 14
    .ChartTitle.Text = chartType(typ) & " Chart."
    .HasDataTable = False
    End With

    'format Pie slices with gradient color
    With grphChart.SeriesCollection(1)
    .HasDataLabels = True
    .DataLabels.Position = xlLabelPositionBestFit
    .HasLeaderLines = True
    .Border.ColorIndex = 19 'edges of pie shows in white color
    For j = 1 To .Points.Count
    With .Points(j)
    .Fill.ForeColor.SchemeColor = Int(Rnd(Timer()) * 54) + 2
    .Fill.OneColorGradient msoGradientVertical, 4, 0.231372549019608
    .DataLabel.Font.Name = "Arial"
    .DataLabel.Font.Size = 10
    .DataLabel.ShowLegendKey = False
    '.ApplyDataLabels xlDataLabelsShowValue
    .ApplyDataLabels xlDataLabelsShowLabelAndPercent
    End With
    Next
    End With

    'Chart Area Border
    With grphChart
    .ChartArea.Border.LineStyle = xlDash
    .PlotArea.Border.LineStyle = xlDot
    .Legend.Font.Size = 10
    End With

    'Chart Area Fill with Gradient Color
    With grphChart.ChartArea.Fill
    .Visible = True
    .ForeColor.SchemeColor = 17
    .BackColor.SchemeColor = 2
    .TwoColorGradient msoGradientHorizontal, 2
    End With

    'Plot Area fill with Gradient Color
    With grphChart.PlotArea.Fill
    .Visible = True
    .ForeColor.SchemeColor = 6
    .BackColor.SchemeColor = 19
    .TwoColorGradient msoGradientHorizontal, 1
    End With

    grphChart.Deselect

    DoCmd.Close acReport, ReportName, acSaveYes
    DoCmd.OpenReport ReportName, acViewPreview

    PieChart_Exit:
    Exit Function

    PieChart_Err:
    MsgBox Err.Description, , "PieChart()"
    Resume PieChart_Exit
    End Function

  2. Press Ctrl+G to display the Debug Window (Immediate Window) in the VBA Editing View, type the following Command in the Debug Window and press Enter:



PieChart "MyReport1", "Chart1"

Sample run image of Option-1 is given below:


Pie Chart Image-1

Sample run image of Option-2:

Sample Run Pie Chart Image-2

Sample run image of Option-3:

Sample Run Pie Chart Image-2

If you prefer to run this command from the On_Click() Event Procedure of a Command Button on your Form, you may do so. The Program will open myReport1 in Design View, resize the Chart1 Chart Object, big enough for Printing or Viewing, and formats the Chart elements. The Program saves the Report and re-opens it in Print Preview.


The Analysis of Values appearing in a PIE Chart is done differently than other form of Charts. That is why PIE Charts take only one set of Values.


If, four of us join together and decided to buy a Cake worth $100 and each one of us take the share of the Cost $6 (I will take the first share amount, if no icing), $60, $20 and $14, the claim on the Cake is in relation to the share of Amount. The Pie Slices will show the size of each one of our share of Cake.


In the earlier examples the Formatting of all the Bars of a particular Data Series are applied together as a single collection of Objects with higher level reference grphChart.SeriesCollection(). But in Pie Chart, individual element of a Data Series (Pie Slices) is referenced by getting one step further deep into the collection of Objects as grphChart.SeriesCollection().Points() and formats them separately with different set of Gradient Colors.


Tips: If you would like to format individual Bars of a Bar Chart you can use this method. But you must remove the following Properties from the Code, used for PIE Chart:


.DataLabels.Position = xlLabelPositionBestFit
.HasLeaderLines = True
.Border.ColorIndex = 19 'showing edges of Pie slices with white color

.ApplyDataLabels xlDataLabelsShowLabelAndPercent


X-Axis and Y-Axis Titles are not used in Pie Charts and these Code segments are removed from the Program. Chart Area and Plot Area are formatted with a different set of light Colors, different from our earlier examples. On these elements also we can use the Rnd() Function to generate different set of values in each Run, for Gradient Color formatting. But, it may not come up with the correct color combination every time, good enough for viewing or Printing. If you do not like the current Scheme Color Values you may try out with different Color Values from the Color Chart given on the first Post Working with Chart Object in VBA.


StumbleUpon Toolbar



Create ListBox from Another ListBox
Selected List Box Items and Dynamic Query
Database Daily Backup
Days in Month Function
Finding Consecutive Workdays with Query

Labels:

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Friday, July 04, 2008

Column Chart and VBA

In our earlier example, Working with Graph Chart in VBA, we have made preparations to try out Charts with VBA and did sample Runs for three Types of Charts viz. Column Clustered, Line Chart and Pie Chart. If you have landed on this page for the first time you may go to the earlier Post by clicking on the Link above. Go through the simple preparations explained there, by following Steps 2 to 7, to try out the Code given here.


Earlier, we could change the Chart type through Code to one of three Types with common property settings that can be applied to all the three. But we have conditionally skipped some properties not relevant to PIE Chart, like Axis Titles. We will deal with PIE Chart separately later and will see how to format individual Pie Slices and change other settings as well.


Here, we will try only one Category of Chart viz. Column Type and will run the Code for 4 different designs. This type of Chart with vertical Bars is the most commonly used Charts and loosely referred to as Bar Chart. The Category Description of the Values plotted on the Chart are placed horizontally along the X-Axis, below the Chart and the Scale calculated automatically and placed vertically at the left side of the Chart (on Primary Y-Axis) with fixed intervals of values. This can be set manually too, if needed.


When very small Values are plotted along with Large Values on the Chart the variations of the small values over a period of time may not be clearly visible and may become difficult for any meaningful analysis purposes. In such situations these can be plotted on the Secondary Y-Axis and the Ups or Downs of values will be clearly visible. With the help of data labels the values on the chart become more meaningful.


When 3D Chart Type is selected Y-Axis gives way to Z-Axis for displaying Tick Labels and Axis Titles. The Charts with Horizontal Bars are the real Bar Charts.


We have created options in the Code to run for the following Options:


  1. Column Clustered.

  2. Column Clustered (Reverse Plot Order - flipped upside down)

  3. 3D Column Clustered.

  4. 3D Column Stacked.


There are optional properties in this Code that you can use to change the shape of the Bars to Cone or Cylinder.


In this example we are turning On the HasDatatable Property of Chart Object that will display the Source Data Table on the Chart. The X-Axis Category Labels Qrtrl to Qrtr4 becomes part of the Data Table display and if we attempt to use the X-Axis Tick-Label Property to set Font or Font Size we will run into errors. We have used it conditionally without eliminating the code altogether so that you will know the difference.


DataLabels Orientation Property gives us the ability to display the Data Labels tilted to a specified Angle in Degrees, besides normal Horizontal or Vertical formats. To try out the examples do the following:


  1. Copy and Paste the following Code in a Global Module of your Database and save it. If you have already gone through the earlier Post and gone through Step-2 to 7 then you are ready to run the Code.


  2. Public Function ColumnChart(ByVal ReportName As String, _
    ByVal ChartObjectName As String)
    '---------------------------------------------------
    'Author : a.p.r. pillai
    'Date : June-2008
    'URL : http://www.msaccesstips.com
    'Customized Source Code : from Microsoft Access Help
    '---------------------------------------------------
    Dim Rpt As Report, grphChart As Object
    Dim msg As String, lngType As Long, cr As String
    Dim ctype As String, typ As Integer, j As Integer
    Dim db As Database, rst As Recordset, recSource As String
    Dim colmCount As Integer, chartType(1 To 6) As String
    Const twips As Long = 1440

    On Error GoTo ColumnChart_Err

    chartType(1) = "Clustered Column"
    chartType(2) = "Reverse Plot Order"
    chartType(3) = "3D Clustered Column"
    chartType(4) = "3D Stacked Column"
    chartType(5) = "Quit"
    chartType(6) = "Select 1-4, 5 to Cancel"

    cr = vbCr & vbCr
    msg = ""
    For j = 1 To 6
    msg = msg & j & ". " & chartType(j) & cr
    Next

    ctype = "": typ = 0
    Do While typ < 1 Or typ > 4
    ctype = InputBox(msg, "Select Chart Type")
    If Len(ctype) = 0 Then
    typ = 0
    Else
    typ = Val(ctype)
    End If
    Loop

    Select Case typ
    Case 5
    Exit Function
    Case 1,2
    lngType = xlColumnClustered
    Case 3
    lngType = xl3DColumnClustered
    Case 4
    lngType = xl3DColumnStacked
    End Select

    DoCmd.OpenReport ReportName, acViewDesign
    Set Rpt = Reports(ReportName)

    Set grphChart = Rpt(ChartObjectName)

    grphChart.RowSourceType = "Table/Query"
    recSource = grphChart.RowSource

    If Len(recSource) = 0 Then
    MsgBox "RowSource value not set, aborted."
    Exit Function
    End If

    'get number of columns in chart table/Query
    Set db = CurrentDb
    Set rst = db.OpenRecordset(recSource)
    colmCount = rst.Fields.Count
    rst.Close

    With grphChart
    .ColumnCount = colmCount
    .SizeMode = 3
    .Left = 0.2917 * twips
    .Top = 0.2708 * twips
    .Width = 5 * twips
    .Height = 4 * twips
    End With

    grphChart.Activate

    'Chart type, Title, Legend, Datalabels,Data Table
    With grphChart
    .chartType = lngType
    If typ = 3 Or typ = 4 Then ' for 3D Charts only
    .RightAngleAxes = True
    .AutoScaling = True
    End If
    .HasLegend = True
    .HasTitle = True
    .ChartTitle.Font.Name = "Verdana"
    .ChartTitle.Font.Size = 14
    .ChartTitle.Text = chartType(typ) & " Chart."
    .HasDataTable = True
    .ApplyDataLabels xlDataLabelsShowValue
    End With

    'apply gradient color to Chart Series
    For j = 1 To grphChart.SeriesCollection.Count
    With grphChart.SeriesCollection(j)
    '.Interior.Color = RGB(Int(Rnd(j) * 200), Int(Rnd(j) * 150), Int(Rnd(j) * 175))
    .Fill.OneColorGradient msoGradientVertical, 4, 0.231372549019608
    .Fill.Visible = True
    .Fill.ForeColor.SchemeColor = Int(Rnd(Timer()) * 54) + 2
    '.Barshape = xlCylinder ' xlCylinder, xlConeToPoint, xlBox, xlPiramidtoMax
    If typ = 1 Then
    .Interior.Color = msoGradientVertical
    End If
    .DataLabels.Font.Size = 10
    .DataLabels.Font.Color = 3
    If typ = 1 Then
    .DataLabels.Orientation = xlUpward
    Else
    '.DataLabels.Orientation = xlHorizontal
    .DataLabels.Orientation = 45 'titlted angle in degrees
    End If
    End With
    Next

    'Y-Axis /(Z-Axis for 3D) Title
    With grphChart.Axes(xlValue)
    If typ = 2 Then
    .ReversePlotOrder = True 'flips upside down
    Else
    .ReversePlotOrder = False
    End If
    .HasTitle = True
    .HasMajorGridlines = True
    With .AxisTitle
    .Caption = "Values in '000s"
    .Font.Name = "Verdana"
    .Font.Size = 12
    .Orientation = xlUpward
    End With
    End With

    'X-Axis Title
    With grphChart.Axes(xlCategory)
    .HasTitle = True
    .HasMajorGridlines = True
    .MajorGridlines.Border.Color = RGB(0, 0, 255)
    .MajorGridlines.Border.LineStyle = xlDash
    With .AxisTitle
    .Caption = "Quarterly"
    .Font.Name = "Verdana"
    .Font.Size = 10
    .Font.Bold = True
    .Orientation = xlHorizontal
    End With
    End With

    'Primary Y/Z Axis values label's font size
    With grphChart.Axes(xlValue, xlPrimary)
    .TickLabels.Font.Size = 10
    End With

    'X-Axis category Labels (Qrtr1, Qrtr2...)
    If grphChart.HasDataTable = False Then
    With grphChart.Axes(xlCategory)
    .TickLabels.Font.Size = 8
    End With
    Else
    grphChart.DataTable.Font.Size = 9
    End If

    'Chart Area Border
    With grphChart
    .ChartArea.Border.LineStyle = xlDash
    .PlotArea.Border.LineStyle = xlDot
    .Legend.Font.Size = 10
    End With

    'Chart Area Fill with Gradient Color
    With grphChart.ChartArea.Fill
    .Visible = True
    .ForeColor.SchemeColor = 2
    .BackColor.SchemeColor = 19
    .TwoColorGradient msoGradientHorizontal, 2
    End With

    'Plot Area fill with Gradient Color
    With grphChart.PlotArea.Fill
    .Visible = True
    .ForeColor.SchemeColor = 2
    .BackColor.SchemeColor = 42
    .TwoColorGradient msoGradientHorizontal, 1
    End With

    grphChart.Deselect

    DoCmd.Close acReport, ReportName, acSaveYes
    DoCmd.OpenReport ReportName, acViewPreview

    ColumnChart_Exit:
    Exit Function

    ColumnChart_Err:
    MsgBox Err.Description, , "ColumnChart()"
    Resume ColumnChart_Exit
    End Function

  3. Insert a new MS-Office Graph Chart Object on a new Report, change the basic property values as given in the earlier Article (Working with Graph Chart in VBA) and save the Report with the name myReport2. We can use the same Table that we have created for earlier examples.


  4. NB: Always create a new Chart Object for new set of examples rather than using the same Chart created earlier. Some property changes found not reflecting correctly when re-used for different Chart Types.


  5. Run the Code either from a Command Button Click Event Procedure or open the Code Module (Alt+F11), display the Debug Window (Immediate Window) with Ctrl+G and type the following and press Enter Key.


  6. ColumnChart "myReport2", "Chart1"

  7. A Menu will appear with four Column Chart Options. Type 1 in the Text Box and press Enter key to run the first option.


  8. The Program Opens the Report myReport2 in Design View, modifies the Chart Properties, saves the Report with the Chart and then re-opens it in Print Preview. A sample run image is given below.


    Image 1 Column Clustered (Normal Plot Order)

  9. Run the Program again and this time select Option number 2.

In this run we are setting the ReversePlotOrder property value to True to Flip the Chart upside down. The sample image is given below.


Image 2 Column Clustered (Reverse Plot Order)


Every time when you run the Code, the Chart Bar Colors are selected at Random order from the Color Chart given in the earlier Post (Working with Graph Chart in VBA) and will display the Chart Bars differently.


If you plan to save the Chart and don't like the Color combination currently displayed you may run the option more than once till you get the color combination to your liking. If you want to save the current run of the Chart you may make a copy of the Report or Export the Report into MS-Access Snapshot Viewer Format (MS-Access 2000 or later).


Chart Area and Plot Area are set with light Gradient Color so that they will look better when printed.


Sample Run of Option 3.


Image of 3D Column Clustered Chart

Sample Run of Option 4.


Image of Column Stacked Bar Chart)

In Option 3 and 4 Runs you can see that the Plot Area of the Chart is extended to display the Data Table and X-Axis Title. But, in the first two runs these are appearing outside the Plot Area.

You can copy and paste the finished Chart into Power Point Presentations. Before transporting the Chart to Power Point page, copy and paste the Values from the Table into the Data Grid of the Chart so that you can edit the values in power point itself, if needed.


  1. Double-Click on the Chart Object in Report Design View to activate the Chart and to display the Data Grid.

  2. Open the Table in Datasheet-View, click on the left top corner of the Table to highlight all the records.

  3. Select Copy from Edit Menu.

  4. Right-Click on the left-top corner cell of the Data Grid and select Paste from the displayed shortcut Menu.




StumbleUpon Toolbar



Selected List Box Items and Dynamic Query
Database Daily Backup
Days in Month Function
Finding Consecutive Workdays with Query
Transparent Command Buttons

Labels:

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Friday, June 27, 2008

Working with Chart Object in VBA

Working with Chart Object in VBA is a complicated matter, but interesting too. Once the code is developed it is very useful and can be used across Applications to prepare Graph Charts with the same look and feel in minutes. There are several Chart Types, Chart Areas and numerous Object Groups and Objects to work with. The Range of values that can go into them, are too many. There are Chart Type specific properties and value-ranges, like the Auto Scaling property that can be used only for 3D Charts.


I did some searching, experimenting and created a VBA Routine that can modify the Graph Chart elements with beautiful formatting to my liking. I hope you will like it too. The sample run result image is given below.





Sample run image




Resizing of Graph Chart and formatting of several elements, like Chart Title, Axis Titles, Chart Area, Plot Area and Chart Bars with Gradient color, Legends, Grid Lines, Data Labels and alignment of Data Labels are done with VBA Code. Placing a Chart Object on the Report with few property changes, as a starter kit, are done manually.


When the Program is run, it gives three options to choose from:


  1. Bar Chart

  2. Line Chart

  3. Pie-chart.


The same Graph Chart is transformed into any one of these Types and the sample values from a Table is used for all the three. Pie-Chart will only use the first record from the Table and the treatment of values in a pie-chart is different from Bar Chart or Line Chart. Here, it is used only for example purposes and Pie-chart is not treated separately.


The following Color index numbers can be used in different combination in Program to get different shades of gradients.




Scheme Color codes



Follow the few simple steps explained below to get prepared for the trial run.


  1. Create a Table with the following Structure and save it with the name Table1.



    Values for Chart



  2. Add the sample records with the values shown above.

  3. Open a new Report in Design View.

  4. Select Object… from Insert Menu and select Microsoft Graph 2000 Chart (or Microsoft Graph Chart in MS-Access 2003) from the Object Type List.


  5. The inserted chart object with default values will be in an activated state, displaying the default values in the Data Grid.





    Default Chart Image



  6. Click outside the chart on the Detail Section of the Report to de-activate and de-select the Chart.

  7. Click on the Chart again to select it and display the Property Sheet (View - - >Properties).

  8. Change the following Property Values as given below:


    • Name : Chart1

    • Row Source Type : Table/Query

    • Row Source : Table1

    • Column Heads : Yes


    Even though the following properties can be changed manually, these are changed through Code:


    • SizeMode : 3 (Zoom)

    • ColumnCount : Number of Colums in the Source Data

    • Left : 0.2917"

    • Top : 0.2708"

    • Width : 5.5729"

    • Height : 4.3854"



    A 2D Chart Object has 3 different areas:


    1. the outer Frame

    2. Chart Area where Chart Title, Axis Titles and Legend Values appears.

    3. Plot Area where the chart Data Series Values, Data Labels, Gridlines, Scale and Category Values appear in Bar or Line Charts.


    If the SizeMode property set to Clip (value 0) then resizing the Chart with the last four values (Left, Top, Width & Height given above) will only change the size of the outer Frame. The inner Sections Chart Area and Plot Area will not resize with the change. If it is set to Stretch or Zoom(Values 1 or 3 respectively) then they will resize to fit within the outer frame area. Zoom is a better setting because it will maintain the Chart in the correct proportions when re-sized, without distortion.


    The Column count property value is found from the Row Source Table or Query String.


    We are validating the settings in Row Source Type property. If it is not set with the value Table/Query then it will change to that value. But, if the Row Source property is not set with a Table Name or valid SQL String then the program will terminate with a message.


  9. Save the Report with the Name myReport1.

  10. Copy and Paste the following VBA Code into the Global Module and save the Module.


  11. Public Function ChartObject(ByVal ReportName As String, _
    ByVal ChartObjectName As String)
    '------------------------------------------------
    'Author : a.p.r. pillai
    'Date : June-2008
    'Source Code : from Microsoft Access Help
    'and modified certain parameters
    '------------------------------------------------
    Dim Rpt As Report, grphChart As Object
    Dim msg As String, lngType As Long, cr As String
    Dim ctype As String, typ As Integer, j As Integer
    Dim db As Database, rst As Recordset, recSource As String
    Dim colmCount As Integer
    Const twips As Long = 1440

    On Error GoTo ChartObject_Err

    cr = vbCr & vbCr

    msg = "1. Bar Chart" & cr
    msg = msg & "2. Line Chart" & cr
    msg = msg & "3. Pie Chart" & cr
    msg = msg & "4. Quit" & cr
    msg = msg & "Select Type 1,2 or 3"

    ctype = "": typ = 0
    Do While typ < 1 Or typ > 4
    ctype = InputBox(msg, "Select Chart Type")
    If Len(ctype) = 0 Then
    typ = 0
    Else
    typ = Val(ctype)
    End If
    Loop

    Select Case typ
    Case 4
    Exit Function
    Case 1
    lngType = xlColumnClustered
    Case 2
    lngType = xlLine
    Case 3
    lngType = xl3DPie
    End Select

    DoCmd.OpenReport ReportName, acViewDesign
    Set Rpt = Reports(ReportName)

    Set grphChart = Rpt(ChartObjectName)

    grphChart.RowSourceType = "Table/Query"
    recSource = grphChart.RowSource

    If Len(recSource) = 0 Then
    MsgBox "RowSource value not set."
    Exit Function
    End If

    'get number of columns in chart table/Query
    Set db = CurrentDb
    Set rst = db.OpenRecordset(recSource)
    colmCount = rst.Fields.Count
    rst.Close

    With grphChart
    .ColumnCount = colmCount
    .SizeMode = 3
    .Left = 0.2917 * twips
    .Top = 0.2708 * twips
    .Width = 5.5729 * twips
    .Height = 4.3854 * twips
    End With

    grphChart.Activate

    'Chart type, Title, Legend, Datalabels,Data Table
    With grphChart
    .ChartType = lngType
    '.ChartType = xl3DColumnClustered
    '.AutoScaling = True ' only for 3D type
    .HasLegend = True
    .HasTitle = True
    .ChartTitle.Font.Name = "Verdana"
    .ChartTitle.Font.Size = 14
    .ChartTitle.Text = "Revenue Performance - Year 2007"
    .HasDataTable = False
    .ApplyDataLabels xlDataLabelsShowValue
    End With

    'apply gradient color to Chart Series
    If typ = 1 Or typ = 2 Then
    For j = 1 To grphChart.SeriesCollection.Count
    With grphChart.SeriesCollection(j)
    '.Interior.Color = RGB(Int(Rnd(j) * 200), Int(Rnd(j) * 150), Int(Rnd(j) * 175))
    .Fill.OneColorGradient msoGradientVertical, 4, 0.231372549019608
    .Fill.Visible = True
    .Fill.ForeColor.SchemeColor = Int(Rnd(1) * 54) + 2
    If typ = 1 Then
    .Interior.Color = msoGradientVertical
    End If
    .DataLabels.Font.Size = 10
    .DataLabels.Font.Color = 3
    If typ = 1 Then
    .DataLabels.Orientation = xlUpward
    Else
    .DataLabels.Orientation = xlHorizontal
    End If
    End With
    Next j
    End If

    If ctype = 3 Then GoTo nextstep 'skip axes for pie chart

    'Y-Axis Title
    With grphChart.Axes(xlValue)
    .HasTitle = True
    .HasMajorGridlines = True
    With .AxisTitle
    .Caption = "Values in '000s"
    .Font.Name = "Verdana"
    .Font.Size = 12
    .Orientation = xlUpward
    End With
    End With

    'X-Axis Title
    With grphChart.Axes(xlCategory)
    .HasTitle = True
    .HasMajorGridlines = True
    .MajorGridlines.Border.Color = RGB(0, 0, 255)
    .MajorGridlines.Border.LineStyle = xlDash
    With .AxisTitle
    .Caption = "Quarterly"
    .Font.Name = "Verdana"
    .Font.Size = 10
    .Font.Bold = True
    .Orientation = xlHorizontal
    End With
    End With

    With grphChart.Axes(xlValue, xlPrimary)
    .TickLabels.Font.Size = 10
    End With
    With grphChart.Axes(xlCategory)
    .TickLabels.Font.Size = 10
    End With

    nextstep:

    With grphChart
    .ChartArea.Border.LineStyle = xlDash
    .PlotArea.Border.LineStyle = xlDot
    .Legend.Font.Size = 10
    End With

    'Chart Area Fill with Gradient Color
    With grphChart.ChartArea.Fill
    .Visible = True
    .ForeColor.SchemeColor = 2
    .BackColor.SchemeColor = 19
    .TwoColorGradient msoGradientHorizontal, 2
    End With

    'Plot Area fill with Gradient Color
    With grphChart.PlotArea.Fill
    .Visible = True
    .ForeColor.SchemeColor = 2
    .BackColor.SchemeColor = 10
    .TwoColorGradient msoGradientHorizontal, 1
    End With

    grphChart.Deselect

    DoCmd.Close acReport, ReportName, acSaveYes
    DoCmd.OpenReport ReportName, acViewPreview

    ChartObject_Exit:
    Exit Function

    ChartObject_Err:
    MsgBox Err.Description, , "ChartObject()"
    Resume ChartObject_Exit
    End Function


  12. Open the VBA Module that you have pasted the Code, if you have closed it.

  13. Run the code from the Debug Window (press Ctrl+G to display Debug Window) using the following Syntax:


  14. ChartObject "myReport1", "Chart1"

    Or call the function from On_Click() Event Procedure of a Command Button on a Form.


  15. Select the Chart Type 1, 2 or 3 for Bar Chart, Line Chart or Pie respectively.


The Program will open the Report myReport1 in Design View, modifies the Graph Chart for the selected Type, Saves it and then Re-opens it in Print Preview. You may minimize the VBA Window (Alt+F11) to view the Chart. Since, the Report is saved after the changes, you may open it manually in design view or Print Preview.


When you run the Code for Bar Chart or Line Chart, the Gradient Scheme Color Codes are selected Randomly, which will give different shades of Gradient Colors every time.


NB: Any suggestions for improvement are welcome.


StumbleUpon Toolbar




Database Daily Backup
Days in Month Function
Finding Consecutive Workdays with Query
Transparent Command Buttons
Colorful Command Buttons

Labels:

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Wednesday, September 05, 2007

MS-Access and Graph Charts2

Continued...

If you have landed straight on this page please go through the earlier Post MS-Access & Graph Charts and then continue.

Sample Data for Pie-Chart


Pie_Table


Desc Veh_Sales Parts_Sales Service_Sales


Total Sales 450000 645000 25000



  1. Create a Table with the above structure and data and save it with the name pie_Table.

  2. Open a new Report in design view. Select Object… from Insert Menu, select Microsoft Graph Chart and Click OK. A Chart Object with default values is inserted on the Report.

  3. Click outside the chart on the report to de-select the chart and to come out of Edit Mode. Click again on the chart to select it, display the property sheet and change the following values:


    • Size Mode = Zoom

    • Row Source Type = Table/Query

    • Row Source = Pie_Table

    • Column Heads = Yes

    • Left = 0.3”

    • Top = 0.3”

    • Width = 6.0”

    • Height = 4.0”


  4. Double Click on the Chart. The Chart Formatting Toolbar will appear on the top. Select 3-D Pie Chart from the Chart Type Toolbar Options or Right-Click on an empty area within the Chart, click on the Chart Type option from the Shortcut Menu and select 3-D Pie Chart.

  5. Open the Pie_Table, click at the left top corner of the Grid and select Copy from Edit Menu.

  6. Click on the top left corner of the Chart Datasheet and Paste the copied value into the Grid.

  7. Delete the extra rows or columns of the sample data left in the Datasheet.

  8. Click on the shaded area around the Pie to select it, click and drag the right bottom corner sizing control to make the Pie little larger. Right-Click on the shaded area around the Pie and select Format Plot Area, select None from the Area options and select None under the Border Options.

  9. Right-click on an empty area of the Chart and select Chart Options from the Shortcut Menu.

  10. Select Title Tab and type Total Revenue in the Chart Title control.

  11. Click on the Data Labels Tab and select Percentage from Label Contains options and click OK to update the Chart Options.




Pie Chart Image


Pie Chart Image.

Chart with more than one set of Bars

Table1


Desc qtr1 qtr2 qtr3 qtr4

A_Revenue 25000 35000 20000 40000

B_Expenses 15000 20000 13000 17000

C_Income 10000 15000 7000 23000



Create a Table with the above Field Structure and Data and save it with the name Table1. Go through the same procedure that we have used in the earlier Post MS-Access and Graph Charts from Step-4 onwards to create the Chart below. In Step-5 change the Property Row source = Table1

Finished Bar Chart created with the above sample data for monitoring the Quarterly performance of individual Area: Revenue, Expenses and Income is given below.



Chart with 3 Bars

The Y-Axis Scale of the Chart and the Major Unit Value intervals (0, 5000, 10000 etc.) are also calculated automatically by MS-Access and displayed on the Chart. There are times that we need to modify the Y-Axis Scale Major Unit intervals to smaller values, when there are smaller values on the Chart items. We can customize the Scale Values if we need smaller units on the Scale.

Double-Click on the Chart to edit it. Right-click on the Y-Axis Line (the vertical line near to the scale values) and select Format Axis option to display the Menu. Select Scale Tab and change the values as follows:


  • Minimum = 0

  • Maximum = 51000

  • Major Unit = 3000




Scale Change Image

Leave the other values unchanged. Click OK to update the new scale settings on the Chart.

Once you change these settings manually it remains unchanged even if the actual value of the Chart crosses the Maximum value settings on the Scale. When it does then you must change the value manually to show the Chart Values correctly or put check mark on all settings to calculate the scale values automatically by MS-Access.

You can change the Alignment of the Chart Data Labels. Right-Click on one of the Labels and select Format Data Labels from the Shortcut Menu. Select the Alignment Tab and click on one of the diamond like symbol in the Orientation options. Experiment with the other options on the Alignment Tab.

We can display the actual data table Values that we have used for the Chart along with the Chart. Double-Click on the Chart. Right-Click on an empty area of the Chart, away from the plot area, and select Chart Options. Select the Data Table Tab and put check mark on Show data Table option.



Data Table View


There are times that we have to use very small values along with very large values on the same Chart. Assume that the Income Values on the above Chart in all four Quarters are less than 3000 mark and the Bars or Lines (in Line Graph) of those set of values may not show big enough to compare them properly.

In such situations we can use the Secondary Y-Axis to calculate the scale of the smaller values and the visibility of the Bars or Lines will be good on the Chart. The presence of Data Labels on the Graph is very important. A sample Image of the above Chart with the Income Values (Blue Colored Bars) plotted on the Secondary Y-Axis is given below:



Secondary Y-Axis Image


To reduce the thickness of the Blue Bars to make it as narrow as the other Bars we have to increase the gap between Bars. Double-Click on the Chart to invoke edit mode. Right-Click on one of the Blue Bars, select Format Data Series and change the Gap-Width Value to 340 in Options Tab and click OK to update the change on the Graph.

The Image of a Chart plotted with the same values in Custom Chart Type: Tubes is given below:



Custom Chart Type:Tubes



Highlighting Reports
Draw Page Border on Reports
Saving Data on Forms

Labels:

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Wednesday, August 29, 2007

MS-Access and Graph Charts

Access Reports are excellent in presenting information in Numbers and Text. But, Charts goes one step further in providing information in the form of pictures and a quick look at them says it all. If we know the simple rule that goes for a Chart then we can create Charts in Access. The simple rule is: show the change of an event over a period of time in the form of dots and lines in relation to the numbers that they represent rather than in numbers and text itself. You must know how to create MS-Access data into a form suitable for preparation of Graphs. To get some familiarity we will look into some examples that uses only one set of values and the data format that is needed for the graph.

Events like the daily change of day temperature or the change of body temperature. of patients in a hospital, to monitor their condition, or the change of Gold price over a period of time etc. can be plotted in the form of Line/Bar Charts on a Graph Paper manually. The Scale of the Chart can be determined and marked based on the maximum available value or more with a fixed interval from 0 at the bottom to the top of the Y-Axis (Vertically at the left side or right side – Secondary Y-Axis - of the Graph). Each day’s value must be marked on the graph paper with a dot in relation to the Scale height at the left side and the dots can be joined with lines. The actual value must be placed near the dot. Date will be written at the bottom of the Graph horizontally (X-axis). The description of the Values plotted on the graph like Gold Price is placed as Legend on the Graph. Instead of Pencil and Paper we can do the same thing with the help of Microsoft Graph Chart Object.

We plan to monitor the daily Stock Index and the values are recorded in an Access Table as given below.


Desc  Date  Val
Stock Index 01-08-07 1245
Stock Index 02-08-07 1455
Stock Index  03-08-07 1395
Stock Index  04-08-07 1575
Stock Index  05-08-07 1125
Stock Index  06-08-07 1000
…….

OR
 
             01-08-07   02-08-07   03-08-07   04-08-07   05-08-07   06-08-07
Stock Index  1245       1455       1395       1575       1125       1000



Sample Chart Image

When the above data is plotted in the form of Charts, the contour of the Charts shows the trend of the stock index at a glance rather than reading the numbers and comparing them.

Before preparing the data for the Chart we must decide what Type of Chart is best suited for the data.

For example: If we are presenting a Chart on the Company’s Total Revenue from various sources like Vehicle Sales, Parts Sales & Service Sales and to show the share of each value to the Total then Pie-Chart will be ideal one for it.

But, if all the three values of the Pie-Chart (Vehicle Sales, Parts Sales & Service Sales) need to be plotted separately showing month-wise performance of each category then Line Chart or Bar Chart will be suitable.

If the source data for the graph changes on a fixed interval, say every month, then the data source object like Table or Query must be prepared keeping this aspect in mind so that the data automatically appears on the Chart when the source data changes, without manually modifying the Chart every time.

Preparing Charts in Access is not as easy as in Excel. We will look into the most commonly used Chart Types: Line, Bar & Pie Chart examples in Access.

The Sample Source Data presented in the first format above must be changed into the 2nd format to create both Line and Bar Charts. In Excel both formats are valid. With the help of a Cross-Tab Query we can change the data format for the Chart.


  1. Create a Table with the Field Names Desc, Date & Val and save it with the name Stock1.

  2. Key-in the six records from the sample data above, as we normally maintain data in Access Tables.

  3. Display the SQL Window of a new Query (don’t select a table or Query from the list displayed), copy and paste the SQL String of a Cross-Tab Query given below into the SQL Window and save it with the name BarChartQ.


  4. TRANSFORM Sum(Stock1.Val) AS SumOfVL
    SELECT Stock1.Desc
    FROM Stock1
    GROUP BY Stock1.Desc
    PIVOT Stock1.Date;


  5. Open a new Report in design view. Select Object… from Insert Menu (Chart Option on the View Menu uses only six Fields for a Chart), select Microsoft Graph Chart and Click OK. A Chart Object with default values is inserted on the Report.

  6. Click outside the chart on the report to de-select the chart from Edit mode. Click again on the chart to select it, display the property sheet and change the following values:


    • Size Mode = Zoom

    • Row Source Type = Table/Query

    • Row Source = BarChartQ

    • Column Heads = Yes

    • Left = 0.3”

    • Top = 0.3”

    • Width = 6.0”

    • Height = 4.0”


  7. Double Click on the Chart. The Chart Formatting Toolbar will appear on the top. Select Column Chart from the Chart Type Toolbar Options or Right-Click on an empty area within the Chart and select Chart Type from the Shortcut Menu and select Column Chart.


  8. Bar Graph in Design View

    In design view the Chart object displays a chart with sample data in an Excel like data Sheet (if not visible double-click on the chart). But, when the Report is Print previewed the Chart will appear with the actual data from the Table/Query we have attached as Source. To see the result of the Source Data in Design View also copy and paste the Source Data into the Excel like Cells.

    Minimize the Report that we are working on. Click on the Query Tab. Double-Click on the BarChartQ to open it. Click at the left top corner of the Datasheet display to select full data. Click the Copy Toolbar Button or select Copy from Edit Menu. Restore the Report with the Chart and double-click on the Chart to display the Data Grid. Click on the left top corner of the Grid to select all the cells. Click the Paste Button on the Toolbar or select Paste from Edit Menu. Click at the left border of the extra two lines below and select cut from Edit Menu to remove the unwanted data. Now the Chart in Design view displays the actual chart values.

    We will format the Chart to give it a better look.

  9. If the Chart is still in the same stage when you have pasted the Chart Values in the Grid (otherwise double-click on it to modify the Chart Options) right-click at the center of the Graph where the shaded area is and away from the Chart Bars. The Plot Area is highlighted; select Format Plot Area… from the Shortcut Menu. Put a check-mark on the None option under Area Options and click OK to close the options menu.

  10. Right-Click on one of the Bars and select Format Data Series… Click on the Fill Effect Button and select Gradient Tab.

  11. Click Vertical under Shading Styles and Click on the Right Bottom Style, out of four Styles displayed. If you want to change the Color of the Bars you can select the color of your choice from the color palette. Accept the default One Color Option without change.

  12. Select the Data Labels Tab. Put a check-mark in the Value Option and click OK to update the change on the Graph.

  13. If the Data Label Font is large then right-click on one of the labels and select Font, Font Style, Size etc. from the Menu and change the values to your liking (say 10 points). Repeat the same change for X-Axis Labels, Y-Axis Labels and Legend.

  14. Right-Click on the Chart outside the Plot Area and select Chart Options.

  15. Type NYSE Index in the Chart Title Control.

  16. Save the Report with the Chart and open it in Print Preview.


  17. Finished Bar Chart Image

  18. Add two more records on the Chart’s Table Stock1. Print Preview the Report with the Chart again and check whether the newly added records are appearing as new Bars on the Chart.


You can create a Line-Chart from the same Bar Chart. Click on the Chart in Design View, Copy and Paste another instance of the same Chart below the Bar Chart. Double-click on the new Chart to Edit the Chart Options. Right-Click on an empty area of the Chart away from the plot area, click on the Chart Type and select Line Chart.



Edit Data in a Zoom-in Window
Saving Data on Forms not in Table
Highlighting Reports
Draw Page Border on Reports

Labels: