Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Opening dBase Files Directly

Introduction

In the earlier article Opening External Data Sources,” we learned how to open another Microsoft Access database and work with its tables using VBA code. I have revised that code from the previous post to include an additional feature — it now displays the database names loaded in Workspace(0) at the top of the list of employee names in the message box.

The revised code is provided below. You can copy it, replace the earlier version, and try it out.

Revised VBA Code.

Public Sub OpenSecondDatabase()
Dim wsp As Workspace, db As Database
Dim rst As Recordset, msg As String, x As Integer
Dim dbcount As Integer

Set wsp = DBEngine.Workspaces(0)
Set db = wsp.OpenDatabase("c:\Program Files\Microsoft Office\Office11\samples\Northwind.mdb")
Set rst = db.OpenRecordset("Employees", dbOpenDynaset)

dbcount = wsp.Databases.Count - 1

msg = ""
For x = 0 To dbcount
 msg = msg & "Database(" & x + 1 & ") " & Dir(wsp.Databases(x).Name) & vbCr
Next
msg = msg & vbCr
With rst
x = 1
Do While x < 6 And Not .EOF
    msg = msg & ![LastName] & vbCr
   .MoveNext
   x = x + 1
Loop
   .Close
End With
MsgBox msg

Set rst = Nothing
Set db = Nothing
Set wsp = Nothing
End Sub

The statement wsp.Databases(x).Name Returns the full path of the database file. To make the display in the message box more concise, I have wrapped it in a Dir() function, which extracts only the file name from the full path. The Dir() function also checks for the existence of the specified file in the given folder, and if it is found, returns just the file name.

Opening dBase Table

Opening the dBase File is comparatively a simple operation. Create an SQL string with a reference to the dBase Database Folder, the Table Name, and the dBase Version (dBase III, IV, or 5.0) of the Table, and open the Recordset directly. The sample SQL String is given below:

strSql = "SELECT Employee.* FROM Employee IN 'C:\MydBase'[DBASE III;];"

If you don't have a dBase file on your Machine to try this out, you can export one of your own Microsoft Access Tables to dBase III, IV, or 5.0 Versions.

I have used the exported Employees Table from the NorthWind.mdb sample database in our example. To try the Code given below without change, you may export the Employees Table from the Northwind.mdb sample database. If you don't know where to find this file, visit the link Saving Data on Forms Not in Table for location references.

Exporting Employees Table as a dBase Table

  1. Create a Folder on your Disk C:\MydBase.

  2. Open the Northwind.mdb database.

  3. Select the Employees table.

  4. Select Export from the File Menu.

  5. Select dBase III or dBase IV, or dBase 5 in the Save as Type Control in the Common Dialog Box.

  6. Browse to the Folder C:\MydBase.

  7. Type the File Name Employee in the File Name Control and Click Export.

Note: dBase Application File uses only 8 characters for the name and 3 characters for File Name Extensions. When you export the Employees Table, it will shorten the name to 8 characters and save it as a dBase table Employee.dbf. The exported Table's Field Names will also be truncated after the 10th character if they are longer.

When the Employees Table is exported in dBase format, several files are created in the output folder depending on the Version of dBase (III, IV, or 5.0) you have selected. The list of files will look like the samples given below:

  1. EMPLOYEE.INF (contains the Index File Details)

  2. EMPLOYEE.DBF (the data, except for the Memo Field Values)

  3. EMPLOYEE.DBT (the Memo Field contents)

  4. LastName.NDX (LastName Field Index information if saved as dBase III)

  5. Postalco.NDX (PostalCode Field Index information if saved as dBase III)

  6. PRIMARYK.NDX (PrimaryKey Index information if saved as dBase III)

If you export a table in dBase IV or 5.0 format, the information contained in the last three files will be consolidated into a single multiple-index file with the MDX extension. The export, import, and link operations are managed by the dBase driver, known as ISAM (Indexed Sequential Access Method), a standard mechanism used by database systems such as dBase and FoxPro (up to version 3.0).

When you attempt to link a dBase table to your MS-Access database, Access will look for all the associated files to load the information correctly. For example, if the file EMPLOYEE.DBT has been deleted from the folder; the table import or link operation will fail with the error: “Cannot locate the XBase memo file.”

You can export the Employees table to dBase IV or 5.0 formats to experiment with SQL syntax for these versions. However, dBase III syntax can also be used to open tables from the later versions.

Having covered all the necessary fundamentals of dBase files, it’s now time to open and work with the data. Copy and paste the code below into a Global Module in your database and save it via File → Save. Place the cursor inside the code and press F5 to run it.

A message box will appear displaying the contents of the LastName field from the Employee.dbf file. If you are using your own dBase file, modify the code to reference your table and field names accordingly.

VBA Code for Opening dBase Table

Public Sub OpenDirectDBF()
'Open DBase File directly and read contents
Dim db As Database, rst As Recordset
Dim strSql As String, i As Integer
Dim msg As String

strSql = "SELECT Employee.* FROM Employee IN 'C:\MydBase'[DBASE III;];"

'Syntax for dBase IV & dBase V
'strSql = "SELECT Employe4.* FROM Employe4 IN 'C:\MydBase'[DBASE IV;];"
'strSql = "SELECT Employe5.* FROM Employe5 IN 'C:\MydBase'[DBASE 5.0;];"

Set db = CurrentDb
Set rst = db.OpenRecordset(strSql, dbOpenDynaset)

i = 0
With rst
msg = ""
Do While Not .EOF And i < 5
   msg = msg & ![LastName] & vbCr
   i = i + 1
   .MoveNext
Loop
MsgBox msg
.Close
End With

Set rst = Nothing
Set db = Nothing
End Sub

Tips: Even if the table name length is more than 8 characters (for example, Employees with 9 characters), the SQL syntax will ignore any characters beyond the eighth, and the file will still open correctly.

You can enable the SQL statements in the code for other dBase versions by removing the single quote (') at the beginning of the line and then running the code.

If you have FoxPro version 2.5 or 3.0 installed on your machine, replace it [DBASE III;] with [FoxPro 2.5;] or [FoxPro 3.0;] to work with those files. Note that later versions of FoxPro require a DSN-based syntax.

Displaying Excel Value directly on the Access Form is next.

Earlier Post Link References:

Share:

Opening External Data Sources

Introduction.

Linking external data sources, such as dBaseExcel, or Tables from another Microsoft Access database, in a Back-EndFront-End setup, is one of the most common and efficient ways to work with data outside the current Database. Once these Data Sources are linked to an Access database, you can easily build queries, design custom Reports, or Design Forms to add or modify data directly within Access, and the source data can remain in its original Application for updates and maintenance.  Linked tables function almost like internal Access tables, with the primary limitation being that their structure cannot be modified from within Access.

To link a Table manually, highlight Get External Data in the File Menu and select Link Tables from the displayed menu. The Common Dialog Box will be displayed, and you can browse to the location of another MS-Access Database, dBase File, or Excel File. Once selected, the available objects will be displayed, and you can link them to your Access database as needed.

If the source data is an Excel database, it is advisable to assign a Range Name (using Insert → Name → Define) to the entire data area before linking it to an MS Access database.

One common issue with Excel-based data sources is that when data is copied and pasted from other applications, such as Word or text files, the column data types can become mixed. As a result, when the table is opened in Access, those columns may display #Error in affected cells due to incompatible data types.

Although Excel provides Data Validation options for manual data entry—such as allowing only integer values in a column, setting character limits (e.g., a maximum of 25), or restricting entries to dates or times—these features are rarely utilized in practice.

So far, we have discussed how to work with external data tables by manually linking them to MS Access. Later, we will explore how to link external files programmatically using VBA, without relying on the menu options mentioned above.

However, if a permanent link to the external table is not required, but the data is still needed temporarily, you can open and work with it directly from Access without creating a link.

Opening a second Access Database

To begin with this method, let us try opening another Microsoft Access database and reading data from one of its tables using VBA code. Later, we will explore similar examples for opening dBase files and Excel databases to retrieve data from those sources as well.

Normally, after launching Microsoft Access, we work with only one database at a time, which remains visible on the application surface—unless it is hidden through the Startup Options. As we know, Microsoft Access is a component-based application consisting of several objects, all organized in a hierarchical structure.

At the top of this hierarchy is the Application object, which we typically open manually whenever we start working in Access. However, it is also possible to create an Access Application object from other systems, such as Visual Basic, and interact with Access databases programmatically.

Next in the hierarchy is the Data Access Objects (DAO) library, which serves as the foundation for working with data. DAO encompasses several key components, including:

  • DBEngine (commonly known as the Jet Engine)

  • Workspaces collection

  • Databases collection

  • User Groups and Users

  • Containers and Documents

  • Table Definitions and Query Definitions

The following diagram illustrates the hierarchical structure of these key components. We will refer to some of them as we proceed to open a secondary database and read the contents of a table from it.

The Jet Database Engine is the core component that powers our work with Microsoft Access databases. It supports multiple Workspaces, and by default, we load or create our databases within Workspace(0).

Database security information—such as User Groups, Users, Personal IDs (PIDs), and Passwords—is managed by Data Access Objects (DAO) and stored in a separate Workgroup Information Database with the mdw file extension.

The name of the active Workgroup file associated with the current Workspace can be verified by checking the DBEngine.SystemDB property. The DBEngine object also maintains the Default User ID and Default Password associated with the active Workspace.

Displaying Workgroup Information File Name.

Type the following command in the VBA Debug Window:

? DbEngine.SystemDB

Sample Output: C:\mdbs\System.mdw

Databases in WorkSpace(0)

Let us return to the topic of Workspace(0) and continue from there. To open a second Microsoft Access database within the same workspace and read or write data to its tables, we must set a reference to DBEngine.Workspaces(0)—the workspace in which our current database resides. You can also modify the table structure, such as by adding a new field, if required.

To demonstrate this with a simple example, we will open the Employees table from the sample Northwind.mdb database and display the contents of the LastName field in a MsgBox using just a few lines of code:

Public Sub OpenSecondDatabase()
Dim wsp As Workspace, db As Database
Dim rst As Recordset, msg As String

Set wsp = DBEngine.Workspaces(0)
Set db = wsp.OpenDatabase("c:\Program Files\Microsoft Office\Office11\samples\Northwind.mdb")
Set rst = db.OpenRecordset("Employees", dbOpenDynaset)

With rst
msg = ""
Do While Not .EOF
    msg = msg & ![LastName] & vbCr
    .MoveNext
Loop
   .Close
End With
MsgBox msg

Set rst = Nothing
Set db = Nothing
Set wsp = Nothing
End Sub

Copy and paste the above code into a Standard Module in your database and save it. Place the cursor anywhere within the code and press F5 to execute it. The LastName field values from the Employees table in Northwind.mdb will be displayed in a MsgBox after the database is closed.

The records are read in a loop to display all nine records available in the table. If you are working with a different table that contains a large volume of records, you can limit the reading cycle by modifying the condition in the Do While Not.EOF statement. This can be achieved with the help of a variable, as shown in the following code snippet.

With rst
msg = ""
X=1
Do While X < 10
    If Not.EOF then
        msg = msg & ![LastName] & vbCr
       .MoveNext
    End If

    X=X+1
Loop
   .Close
End With

The VBA Code.

The reading statements are placed within an If...Then block so that the program cycles through the loop and terminates gracefully without triggering an error if your table contains fewer than nine records. The last three statements release the memory occupied by the objects.

The first line of the code sets a reference to the Workspace(0) object, while the second line opens the Northwind.mdb database within the same workspace. Although this secondary database is not visibly displayed, you can imagine it as being loaded alongside your current database within the same workspace.

The file path shown in the code corresponds to the Microsoft Access 2003 version. In later versions of Access, the path structure may vary slightly after the \Microsoft Office\ directory, but the file will still reside within the \Samples folder. Locate the correct path for your version of Access and update the pathname in the code accordingly.

Next, we will see how to open a dBase File directly and work with it.

Share:

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:

Column Chart and VBA

Introduction.

In our earlier example, working with Access Graph Chart in VBA, we prepared MS Access Charts with VBA and ran sample tests for three types of charts: Clustered Column, Line, and Pie. If this is your first time here, refer to the earlier post by clicking the link above. Follow Steps 2 to 7 to complete the preparations before trying the code presented here.

Previously, we were able to change the chart type in code to any of the three types while applying common property settings. However, some properties, such as Chart Axis Titles, were skipped conditionally for the Pie Chart. We will handle Pie Charts separately later, including formatting individual pie slices and modifying other settings.

Here, we will focus only on Column Charts and run the code for four different designs. Column Charts, with vertical bars, are the most commonly used type and are often loosely referred to as bar charts. The category labels for the plotted values appear horizontally along the X-axis below the chart, while the chart scale is calculated automatically and displayed vertically along the left side (Primary Y-Axis). This scale can also be set manually if needed.

When small values are plotted alongside large values, the differences in the small values may not be clearly visible. In such cases, you can plot the small value series on the Secondary Y-Axis (right-side vertical axis) to make the variations more noticeable. Adding data labels further enhances the readability and analysis of the chart.

For 3D Column Charts, the Y-axis is replaced by a Z-axis to display tick labels and axis titles. Note that horizontal bar charts are the true representation of bar charts.

Sample Demo Run Code

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 a Cone or a Cylinder.

In this example, we enable the HasDataTable property of the Chart Object, which displays the source data table directly on the chart. The X-Axis category labels, Qrtr1 to Qrtr4, become part of this data table display. Note that if you try to modify the X-Axis Tick-Label properties, such as Font or Font Size, while the data table is visible, you may encounter errors. We have included this code conditionally rather than removing it completely, so you can observe the difference.

The DataLabels Orientation property allows you to tilt the data labels to a specified angle in degrees, in addition to the standard horizontal or vertical display.

To try out these examples, follow the steps below:

The VBA Code

  1. Copy and paste the following code into a Global Module of your Database and save it. If you have already gone through the earlier Post and gone through steps 2 to 7, then you are ready to run the Code.
    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
    

    Preparing for Demo Run

  2. 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.

    NB: Always create a new Chart Object for a new set of examples rather than using the same Chart created earlier. Some property changes were found to be shown incorrectly when reused for different Chart Types.

  3. The Code can be tested either by running from a Command Button Click Event Procedure or directly from the Debug Window (Immediate Window). Press Alt+F11 to open the VBA Window,  press Ctrl+G for the Debug Window, and type the following command and press the Enter Key.

    ColumnChart "myReport2", "Chart1"
  4. A menu will appear with four Column Chart Options. Type 1 in the Text Box and press the Enter key to run the first option.

    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.

  5. Run the program a second time, 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.

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

Saving the Report with the Chart.

If you plan to save the Chart and don't like the Color combination currently displayed, 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, 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 a light Gradient Color so that they will look better when printed.

Sample Run of Option 3.

Sample Run of Option 4.

In Options 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.

Saving PowerPoint Presentations.

You can copy and paste the finished Chart into PowerPoint Presentations. Before transporting the Chart to the PowerPoint page, copy and paste the Values from the Table into the Data Grid of the Chart so that you can edit the values in PowerPoint 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, and click on the top left corner of the Table to highlight all the records.
  3. Select Copy from the Edit Menu.
  4. Right-click on the top-left corner cell of the Data Grid and select Paste from the displayed Shortcut Menu.

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:

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