<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;searchRoot=http%3A%2F%2Fblogsearch.google.com%2F&amp;blogLocale=en_US&amp;homepageUrl=http%3A%2F%2Fwww.msaccesstips.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> <div></div>
www.msaccesstips.com

LEARN MS-ACCESS TIPS AND TRICKS


International Response Fund

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:

1 Comments:

Blogger lusia said…

Hi Friend.I keep reading your website.it is very nice.YOUR POSTING IS REAL STATE.plz exchange link.then let me know I will do the same.my url,
www.googleadsensesystem.blogspot.com ,
www.softwareonlinehelper.blogspot.com.
thanks.

July 05, 2008 3:19 PM  

Post a Comment

Note:Comments subject to Review by Blog Author before displaying.

Links to this post:

Create a Link

<< Home


Creative Commons License
Learn MS-Access Tips and Tricks by msaccesstips.com is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.5 India License.



This Page is best viewed with 1280 x 1024 Resolution

   FEATURED LINKS
SITEMAP
Command Button Animation
3D Headings on Forms
MsgBox & Office Assistant
Reminder Ticker
MS-Access & E-Mails
Automated E-Mail Alerts
MsgBox with Options Menu
Colorful Command Buttons
Configure Lotus Notes
Alerts through Network
Running this site has become a costly affair as the revenue from Ads is not sufficient to support it. If you find these pages informative & useful and would like to extend a helping hand, then please do it here.





Link Back to us with this Button

Learn MS-Access

Copy and Paste this HTML Code in your Webpage


Add to Technorati Favorites

Programming Blogs - Blog Catalog Blog Directory
Powered by FeedBurner
Add to Google

Software
Computers blogs
TopOfBlogs




AddMe - Search Engine Optimization Submit Your Site Free!
Go BlogZ Ave Blogs
eBlogzilla Changing LINKS
LS Blogs Blogarama
blog search directory BlogUniverse
Find Blogs in Directory RSS Directory
blogskinny.com ShowcaseBlogs.com
Amfibi

Search Engine Optimization and SEO Tools
Dmegs Web Directory Takeaway for Sale Businesses For Sale
Free Submission Directory Free site submission

Free Listing
 





Free Page Rank Checker

AddThis Social Bookmark Button

Enter your email address:

Delivered by FeedBurner



Top Blogs


Microsoft Access is the Jewell among MS-Office suite of Applications. Its Security features are excellent and works fine in Network environment. MS-Access can link/upload data from any Data Source. Applications that you design should be user-friendly and visually pleasing too. Here I would like to share my experience in Microsoft Access Programming with you and I am sure that you will find them interesting too.

My Photo
Name: Ramachandran Pillai
Location: Cochin, India

I am not an Access Guru and not through MS-Access yet. More to learn and I don’t think that aspect has any end because others have their own style of using this tool. We can learn lot more tricks, other than what we already know, from others too. My programming skills in COBOL, BASIC, Turbo-C, dBase, FoxPro, Visual Basic & Basic HTML attained through self-learning. I wrote my first COBOL Program in 1975 for ICL1901, 3rd Generation Main Frame Computer. Worked as a Computer Operator (NCR VRX8555 Mainframe Machine upto 1990) with M/s. Y.B.A. Kanoo, Saudi Arabia. Started using MS-Access Ver.2 in 1996, when dBase III+ and Foxbase (later version Foxpro) were my favorite DBMS. During Last 13 Year period I have developed more than 45 In-House Applications (medium & small) under MS-Access for our Organization, a leading Automotive Company in Oman. All the Applications are fully Secured and runs under Windows Network. It is my pleasure to share my experience with others. Anything interesting that you would like to share with me, please do. My E-mail Address: aprpillai@msaccesstips.com


If you need a Demo of any of the Topic explained here, send me an E-mail to: aprpillai@msaccesstips.com
with the Topic Description, I shall try to send a sample database to you.


Access Tips | Email | Reports | Report Tricks | Graphs | Forms | Menus | Animation | Security | Internet | How TOs | Linking | Query | Progress Meter | Alerts | Process Tips | Access Functions |




Site Designed by:www.msaccesstips.com