Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

PIE CHART OBJECT AND VBA

Introduction.

This post continues our discussion on working with the Chart Object in VBA. In the earlier article, Working with Chart Object in VBA, we created a small table and a report containing a Chart Object, and we explored a few basic property modifications to prepare for the upcoming VBA demonstrations.

Before proceeding, please review Steps 1 to 7 outlined in the earlier post by following the provided link, and then continue from here.

You will find it helpful to read the related topics, Column Chart and VBA, for additional context and practical examples.

PIE Chart Options.

    If you have already tried the code examples from the earlier posts, you should find most of the segments here familiar and easy to follow. The main differences in this section involve the formatting of individual pie slices and a few property adjustments.

    In this example, we will experiment with three types of Pie Charts:

    1. 3D Pie

    2. 3D Exploded Pie

    3. Pie of Pie

    Each variation demonstrates a different way of emphasizing data segments and controlling the visual layout of your chart through VBA.

  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: an image of Option-1:


Sample run: an image of Option-2:


Sample run: an image of Option-3:


Run it from the Command Button Click.

You can run this program from the On_Click() Event Procedure of a Command Button on your Form. The program will:

  1. Open myReport1 in Design View.

  2. Resize the Chart1 Chart Object to a size suitable for printing or viewing.

  3. Format the chart elements.

  4. Save the report and reopen it in Print Preview.

Key points about PIE Charts:

  • The analysis of values in a Pie Chart differs from other chart types, which is why Pie Charts accept only one set of values.

  • For example, if four people decide to buy a cake worth $100, and their shares are $60, $20, $14, and $6, the Pie Slices will reflect the proportion of each share relative to the total cost.

  • Unlike Bar or Column Charts, where formatting can be applied to an entire data series using grphChart.SeriesCollection() - Pie Charts require you to access individual slices through grphChart.SeriesCollection().Points() - This allows you to apply different gradient colors or formatting to each slice separately.

Tip: You can use the same Points() method to format individual bars of a Bar Chart, but you must remove the Pie-specific properties from the code to avoid errors.

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

Chart Formatting.

In Pie Charts, the X-Axis and Y-Axis titles are not used, so the corresponding code segments have been removed from the program. The Chart Area and Plot Area are formatted using a different set of light colors, distinct from the previous examples.

You can also use the Rnd() function to generate different color sets for each run, applying gradient formatting. However, the resulting color combination may not always be ideal for viewing or printing. If you are not satisfied with the current color scheme, you can experiment with different color values from the Color Chart provided in the first post, Working with Chart Object in VBA.

Download the Demo Database.

Download Demo Database

  1. MS-Access and Graph Charts
  2. MS-Access and Graph Charts-2
  3. Working With Chart Object in VBA
  4. Column Chart and VBA
  5. Pie Chart Object and VBA
  6. Missing Lines in Line-Chart
  7. Pie Chart and Live Data on Form
  8. Scaling Chart Object
  9. Cross-Tab Union Queries for Chart
Share:

4 comments:

  1. Thanks for all this information.

    I created the table and used "number" for each of the fields except the first which is a "text" and is the primary key. When I ran the first part of the program using then command line I got a msg box that was "False" and asking for an entry. Could not get past that.

    So I moved on to the second part, this area, and tried the pie chart. However, I am using 2003 and need to know what the error "Type Mismatch" is when the line:

    With grphChart
    .chartType = lngType
    .....


    runs? Can anyone help.

    ReplyDelete
  2. Download a sample database with all the running programs of charts from the following link:

    http://www.msaccesstips.com/downloads/2008/06/workingwith_chartobject.php

    ReplyDelete
  3. I downloaded the database above and it was helpful. I was a little disappointed that the example here (unlike the bar/column one)was so fancy with no queries, I would have preferred a dumbed down example like the bar/column one where I could follow the code (I am not a programmer). Anyway, I do not seem to be able to get my pie to work when I try to create one from scratch using the chart wizard. I only get a purple pie with a line to the center of it. Then I copied your report and pointed to my query and pasted and also pasted that into the a demo pie and it looked pretty good in that my pie divided into six with labels and values and different colors for each slice.

    The problem is that I need to use percentages. My values/percentages do not match the demo and report view of the data so though it looks ok it is completely wrong.

    My "crosstab" query for each column is:

    79.74% 14.16% 4.47% 1.46% 0.17% 0.00%

    My demo pie and report shows:

    70 22 7 1

    What am I doing wrong?

    Thanks

    Leah

    ReplyDelete
  4. I finally figured out what I was doing wrong. I seem to need an "extra" column with "column name" for my first column. My data was in a crosstab like form (one record with 6 different columns), but it was was not really a crosstab. Access apparently thought that my first column was the column name so it ignored it in the calculation and then all my percentages were off. The strange thing is that I pasted everything starting with the second column but when I closed and came back to it, everything moved.

    ReplyDelete

Comments subject to moderation before publishing.

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code