Microsoft Access VBA Tutorials for self-paced learning, Class Modules, SQL Techniques, and AI Integration Guides.

Wave Shaped Reminder Ticker

Wave-Shaped Reminder Ticker.

We have already seen how to create and install a Reminder Ticker that runs in a straight line on the Main Screen. We could do this with a few lines of VBA code and a Label control on the Main Screen. We will try something different this time. This ticker runs in a Zigzag form. An image of a sample run of this method is given below:

To create this Ticker, we need a series of labels arranged in a wavelike form, and each one must be named in a way that makes it easy to address them in code. A sample design is given below:


Automating the Label Creation.

There are about 42 identical labels to be created. Even if we create them manually once, arranging them in the required zigzag layout is a challenging task. However, this can be done efficiently with a small program. The program generates a new form, creates all 42 labels, arranges them in a zigzag pattern, assigns them sequential names, such as lbl1 through lbl42, and adjusts their other properties as described above.

  1. Copy the following Code into a Global Module of your Database and save it.
    Public Function ZIGZAG()
    '-----------------------------------------------------------
    'Author  :  a.p.r. pillai
    'Date    :  01/10/2008
    'URL     :  www.msaccesstips.com
    'All Rights Reserved by www.msaccesstips.com
    '-----------------------------------------------------------
    Dim frm As Form, ctrl As Label, t As Long, lngleft As Long
    Dim lngwidth As Long, lngheight As Long, lngtop As Long
    Dim j As Integer, k As Integer, h As Long, G As Long
    
    h = 30: G = 0: t = 0
    lngwidth = 0.1146 * 1440
    lngheight = 0.2083 * 1440
    lngtop = 1 * 1440
    lngleft = 0.16667 * 1440
    Set frm = CreateForm
    For j = 1 To 42
    Set ctrl = CreateControl(frm.Name, acLabel, acDetail, , , lngleft, lngtop, lngwidth, lngheight)
    lngleft = lngleft + lngwidth
    With ctrl
        .Name = "lbl" & j
        .FontName = "Tahoma"
        .FontSize = 8
        .Caption = ""
        .BackStyle = 0
        .ForeColor = 255
     End With
     Next
    G = 0
    For j = 1 To 3
         For k = 1 To 7
            G = G + 1
            Set ctrl = frm.Controls("lbl" & G)
            With ctrl
                .Top = .Top - (h * k)
            End With
            DoEvents
         Next
        t = frm.Controls("lbl" & G).Top
         For k = 1 To 7
             G = G + 1
            Set ctrl = frm.Controls("lbl" & G)
            With ctrl
                .Top = t + (h * 1)
            End With
            t = frm.Controls("lbl" & G).Top
            DoEvents
        Next
    Next
    End Function
    
  2. You can run the above Code directly by placing the cursor in the middle of the Code and pressing the F5 Key, or running from a Command Button's On Click Event Procedure or a Macro.

    Each time the code is executed, it creates a new form with the labels arranged in a zigzag pattern. Once you’ve created it, you can export this form to other projects where you want to install the ZigZag Ticker. Alternatively, you can place the code in a common library database and run it from your new project after attaching the library file to your project.

    Placement of the Ticker Labels.

  3. After creating the Labels, click outside the Labels and drag over them so that all the Labels are selected without disturbing the Labels' arrangement.

  4. Select Copy from the Edit Menu.

  5. Open the Main Switch Board (Control Form) in Design View and paste them.

  6. When all the labels are still in the selected state, drag and place the Labels into a position where you want the Ticker to appear on the Form.

    We have two more Sub-Routines, which are run from the Form_Load() and Form_Timer() Event Procedures. In the Form_Load() Event Procedure, we can create a Text Message in a String either with a constant value or with Field Values from a Table/Query that provides useful information to display to the User as a reminder. Refer to the earlier example Reminder Ticker Form, which uses data from within the Application as a reminder.

    Formatting Ticker Text.

    The Form_Timer() Event Procedure will control the Display of Label values, shifting one character at a time in succeeding labels, giving it a sense of motion.

  7. Copy and paste the following Sub-Routines into the Form Module where you have pasted the above labels.

    Option Compare Database
    Option Explicit
    Dim txt As Variant
    
    Private Sub Form_Load()
        txt = Space(42) & UCase("Excellence is not a matter of chance. It is a matter of Change. It is not a thing to be waited for. It is a thing to be achieved.")
        Me.Timerinterval=250
    End Sub
    
  8. See that the Dim txt As Variant is placed in the Global Area of the Module, which is referenced from the Form_Load() and Form_Timer() Event Procedures.

    Private Sub Form_Timer()
    Dim x As String, k As String, j As Integer, ctrl As Control
    
      x = Left(txt, 1)
      txt = Right(txt, Len(txt) - 1)
      txt = txt & x
      k = Left(txt, 42)
    For j = 1 To Len(k)
        Set ctrl = Me.Controls("lbl" & J)
        Ctrl.Caption = Mid(k, j, 1)
    Next
    End Sub 
    

    Disable Ticker on inactive Form.

  9. The following lines of code are useful if you plan to disable the ticker when the Main Form is inactive and run it when the Main Form is active again, so that other processes are not interrupted by the Ticker.

Private Sub Form_Deactivate()
   Me.TimerInterval = 0
End Sub

Private Sub Form_Activate()
   Me.TimerInterval = 250
End Sub

Download


Download Demo Database Access2007.zip



Download Demo Database Access2002-03.zip

Share:

No Data and Report Error

No Data and Report Error.

Report Source Query or Table can end up with no output records. In that case, some of the controls with the formula in the Report will show #Error. An image of a sample report is given below:

The #Error message at the top-right corner appears because the control contains a formula intended to display the reporting period. Similarly, the controls to the right of the word TOTAL—which display subtotals, totals, and detail line values—also show errors. This occurs when the report’s underlying query returns no records for the period selected by the user.

Although this is not a critical issue, it is considered poor practice to present or archive such a report with visible errors, especially if it needs to be shared as a NIL REPORT or retained for audit or future reference.

The modified version of the report shown below resolves this issue. It includes a clear comment, displays zero values in the summary controls, and correctly prints the reporting period.

I have made a few modifications to the Report Design to add a hidden label at the footer of the Report with the Caption: *** Congratulations *** Nothing Pending to show up when there are no output Records for the Report. The Visible Property of the label is set to No. In the Detail Section under the Description Column, it shows *** NIL REPORT ***. The period for which the Report is prepared is also shown to the right, above the Detail Section headings.

The Report Period (DateFrom and DateTo) is normally entered into a Parameter Table and joined with the Report Source Table in a Query to use them for criteria and for displaying on the Report.


Few Changes in the Report

Created two Text Controls (with the names From and To, respectively) at the Report Header Section to the right of the Control name STAFFNAME to load the DateFrom and DateTo Values from the Report Parameter Table with the DLookup() Function:

=DLookUp("DateFrom","Report_Param")

The second control has the expression to read DateTo from the Report_Param Table, and both values are used in the expression (=" Period: " & [frm] & " To " & [To]) to format the values to show the output as in the second image given above. These are all the cosmetic changes required in the Report.

Temporary Table for Report.

The major change is creating a temporary table with a single blank record, which should have the same structure as the Source Table or Query, and attaching it to the Report. If your Report is using a Table as Report Source Data, then make a copy of the structure of the Table and add a tmp_ prefix to the table name, like tmp_myReport. If it is a Query, then create a Make-Table Query using the Report Source Query and create a temporary table. Add a blank record in the temporary table. If your Report Table has a Text Field that is displaying the value on the Report, then type *** NIL REPORT *** in that field. Fill numeric fields with 0 and keep all other fields Empty.

How the Trick Works.

The trick is that when the Report is opened by the User, we will check whether the original Report Source Table or Query has any records in it or not. If not, swap the Temporary Table with the Report Source Table or Query. The hidden Label's Visible Property will be set to Yes to display the comment *** CONGRATULATIONS *** NOTHING PENDING. Since the temporary table has a single blank record, the Summary Controls will not show errors.

We need a few lines of VBA Code in the Report_Open() Event Procedure to check and swap the Report Source Table or Query.

A few lines of VBA Code.

Private Sub Report_Open(Cancel As Integer)
Dim i As Integer
i = DCount("*", "myReport")
If i = 0 Then
   Me.RecordSource = "tmp_MyReport"
   Me.lblMsg.Visible = True
End If
End Sub

Copy and paste the above code in the Report's VBA Module and make changes to insert the correct Table/Query and tmp_myReport names.

Share:

Lost Links of External Tables

Lost Links of External Tables.

We have already learned several methods to work with external data sources. Linking them to an MS Access database or directly opening them in Queries by setting Source Database and SourceConnectStr Properties. In either case, the Source Data must be present in its original location at all times.

However, there is always a possibility that the links to some of these tables may be lost—for instance, if a source table is accidentally deleted or renamed. Such issues typically go unnoticed until we attempt to work with the linked tables, often resulting in errors, which may appear unexpectedly.

To alleviate this problem, run a check on the linked tables as soon as the Database is open for normal operations. If any of the linked Tables are not in place, then warn the User about it and shut down the Application if it has serious implications.

How do we determine whether a linked external table has lost its connection with the Database or not? It is easy to attempt to open the linked table, and if it is in error, you can be sure the table link is missing. 

There may be several tables in a database, local tables or linked ones. How can we single out the linked ones alone and open them to check the status? Again, this is not a serious issue, and you already have the answer if you have gone through the earlier Articles explaining several methods of accessing external data and the usage of Connection Properties of Linked Tables and Queries.

The Connection Property Value.

We need a small VBA routine to iterate through the Table definitions and check the Connect Property value, and if it is set with a Connect String, then it is a linked table; otherwise, it is a local table. When we encounter a linked table, we will attempt to open it to read data. If this process triggers an Error, then we will prepare a list of such cases and display it at the end to inform the User so that she can initiate appropriate remedial action to rectify the error.

A sample VBA routine is given below. Copy and paste the program into a Global Module and save it.

Public Function LostLinks()
'----------------------------------------------------
'Author : a.p.r. pillai
'URL    : www.msaccesstips.com
'Date   : 21/09/2008
'----------------------------------------------------
Dim msg As String, tbldef As TableDef
Dim strConnect As String, cdb As Database
Dim rst As Recordset, strTableName As String
Dim strDatabase As String, loc As Integer
Dim loc2 As Integer

On Error Resume Next

Set cdb = CurrentDb
For Each tbldef In cdb.TableDefs
    strConnect = tbldef.Connect

    If Len(strConnect) > 0 Then
       strTableName = tbldef.NAME
       Set rst = cdb.OpenRecordset(strTableName, dbOpenDynaset)
       If Err > 0 Then
          If Len(msg) = 0 Then
             msg = "The following Linked Tables are missing:" & vbCr & vbCr
          End If
          msg = msg & strTableName & vbCr
          Err.Clear
        End If
        rst.Close
    End If
Next

If Len(msg) > 0 Then
    MsgBox msg, , "LostLinks()"
End If

End Function

Call the Routine from an Autoexec Macro or from the Form_Load() Event Procedure of the Application's Startup or Main Screen.

Earlier Post Link References:

Share:

Link External Tables with VBA

Link External Tables with VBA.

We all know how to link to a table from external data sources manually.

  1. Highlight Get External Data from the File Menu.

  2. Select Link Tables from the displayed options.

  3. Select the file type: dBase, Excel, etc., in the Files of Type control.

  4. Track the location of the file and select it.

  5. Click the link to attach the selected table to the Current Database.

If you are linking an external table from a Network Location, use the UNC (Universal Naming Conventions) type location reference (like \\hosfs03\accounts\myDatabase\...), rather than using a mapped drive location reference like H:\MyDatabase. 

You can even use your Local Drive's share name in this manner. 

\\yourPCName\C$\Databases\myDatabase.mdb

This method ensures that even if the drive mapping changes—for example, from H:\ to K:\ or any other letter—MS Access can still locate the linked tables without issues. Otherwise, you would need to manually update the table locations using Tools → Database Utilities → Linked Table Manager to refresh the changed path references.

We have already seen that we can work with external tables without linking them permanently to the current database.

Here, we will link external Tables to the Current Database using VBA. After linking the table, we will print the contents of five records into the Debug Window and delete the link.

The Steps to follow.

We will go through the following steps to link a Table to a Database with VBA:

  1. Create a temporary Table Definition (Tabledef) without any Field Definitions in the Current Database.

  2. Load the Connect Property of tabledef. with a connection string value

  3. Link the external Table to the temporary Table definition (Tabledef)

  4. Add the temporary Table definition to the Tabledefs Group.

  5. Rename the temporary Table to match the Source Table Name.

The VBA Functions.

We will write two VBA Functions for our examples. Copy and paste the following VBA code into a Global Module of your MS Access Database and save it:

Public Function LinkMain()
Dim strConnection As String
Dim sourceTable As String

strConnection = ";DATABASE=D:\Program Files\Microsoft office\Office\Samples\Northwind.mdb;TABLE=Orders"

sourceTable = "Orders" 'Access Table Name

LinkExternal strConnection, sourceTable

End Function
Function LinkExternal(ByVal conString As String, sourceTable As String)
Dim db As Database, i As Integer, j As Integer
Dim linktbldef As TableDef, rst As Recordset

Set db = CurrentDb
Set linktbldef = db.CreateTableDef("tmptable") 'create temporary table definition

linktbldef.Connect = conString 'set the connection string
linktbldef.SourceTableName = sourceTable 'attach the source table
db.TableDefs.Append linktbldef 'add the table definition to the group
db.TableDefs.Refresh 'refresh the tabledefinitions

linktbldef.NAME = sourceTable 'rename the tmptable to original source table name

'open the recordset and print 5 records in the debug window
Set rst = db.OpenRecordset(sourceTable, dbOpenDynaset)
i = 0
Do While i < 5 And Not rst.EOF
  For j = 0 To rst.Fields.Count - 1
     Debug.Print rst.Fields(j).Value,
  Next: Debug.Print
  rst.MoveNext
  i = i + 1
Loop
rst.Close

db.TableDefs.Delete sourceTable 'remove to stay the table linked
db.Close
Set rst = Nothing
Set linktbldef = Nothing
Set db = Nothing

End Function

How it works.

The first program, LinkMain(), calls the LinkExternal() Subroutine with strConnection and SourceTable name as parameters. Northwind.mdb sample database and Orders Table are passed as parameters. Open the Debug Window (Immediate Window) by pressing Ctrl+G. Click anywhere within the LinkMain() program and press F5 to run the code and print five records of the Orders table from the Northwind.mdb database.

The LinkExternal() Program performs the five steps of action explained above.

Replace the strConnection and sourceTable with the following sample values for opening a dBase Table:

strConnection = "dBase IV;HDR=NO;IMEX=2;DATABASE=D:\msaccesstips" sourceTable = "Branches" 'Access Table Name

Tip: If you don't have a dBase Table to try the Code, then export a Table from MS Access into the dBase format and run the Code with changes.

Change the Database Folder name and the Table name with your own dBase Folder and Table names.

For Excel-based Tables, two methods are given below.

  1. Use Worksheet Reference (Sheet1$) as the source Table location. The $ symbol is necessary with the Worksheet name:

    strConnection = "Excel 5.0;HDR=YES;IMEX=2;DATABASE=D:\msaccesstips\Branch.xls" sourceTable = "Sheet1$" 'Excel Sheet Name Reference
    

    The topmost row contents of the table area will be used as Field Names.

    strConnection = "Excel 5.0;HDR=YES;IMEX=2;DATABASE=D:\msaccesstips\Branch.xls" sourceTable = "BranchNames" 'Excel Range Name Reference
    
  2. Excel Range Name, Branch Names will be used as the Table location. The first line is the same as above for this example, also.

Earlier Post Link References:

Share:

Source Connect Str Property and ODBC

'Source Connect Str' Property and ODBC.

We have already seen that the SourceConnectStr property, when used together with the 'Source Database' property in an MS Access Query, allows us to open and work directly with external data sources such as dBase, FoxPro (Versions 2.5 or 3.0), and Excel tables.

We also learned how to include these property specifications within an 'IN clause' directly in the SQL statement of a query.

However, for data sources such as AS/400 (iSeries), SQL Server, and FoxPro (via newer database engines), Access requires an ODBC (Open Database Connectivity) connection string. This connection string defines how Access communicates with these external systems, specifying the driver, data source name, authentication credentials, and other parameters needed to establish the connection.

ODBC Connection String.

The best way to learn and understand more about the Connection String Syntax of different ODBC Data Sources is to go through the following steps and look at the Connection String of the Linked Table:

  1. Create an ODBC DSN (Data Source Name). Refer to the Post Linking with IBM AS400 Tables.

  2. Link the Table from the source directly using File -> Get External Data -> Link Table.

  3. Select ODBC Databases in the Files of Type control.

  4. Select the ODBC DSN that you have created from the displayed list.

  5. Click OK. If you have not created a DSN, you can create a new one by selecting the New... Command Button.

  6. Select the Table to link with your MS-Access Database.

  7. After linking the Table, select the linked Table.

  8. Select Design from the Database Menu. You will receive a warning message saying that the Linked Table Structure cannot be modified. Click Yes to the Prompt: Do you want to open it anyway?

  9. Display the Property Sheet (View ->Properties).

Description Property of Table.

On the Description Property of the Table Structure, you will find the ODBC String that can be used directly on the Query's SourceConnectStr Property.

A few examples of ODBC Connection String Values are given below:

AS400 (iSeries) Table:
  • ODBC;DSN=myData;UID=UserID;PWD=Password;TABLE=PAVUP.APC161D
SQL Server:
  • ODBC;DSN=MyData;UID=UserID;PWD=Password;DATABASE=Parts
FoxPro:
  • ODBC;DSN=Visual FoxPro Tables;UID=;PWD=;SourceDB=C:\MyFoxpro;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=GENERAL;Null=Yes;Deleted=Yes

As shown in the examples above, the DSN Name, User ID, Password, and other parameters in the ODBC connection string are specific to each data source and must be entered accurately to establish a valid connection to their respective tables.

In the case of the AS400 (iSeries) ODBC connection string, the table name and library (or folder) name are separated by a dot (.), following the convention used in IBM systems, for example, `MYLIB.MYTABLE`.

For more details on setting up such connections, you can refer to the earlier discussion titled “Linking with IBM AS400 Tables”, which explains how to properly link AS400 (iSeries) tables to a Microsoft Access database using ODBC drivers and connection parameters.

Earlier Post Link References:

Share:

Access Live Data in Excel-2


Continued from last week's post
:

This is a continuation of the earlier post Access Live Data in Excel. Please refer to the earlier article before continuing.

If you want to make changes to the Query that you have created for bringing Access Data into Excel, you may do so.

  1. Click on a cell within the Data Area on the Worksheet.

  2. Point to Import External Data (Get External Data in MS Office 2000) in the Data Menu.

  3. Select Edit Query from the displayed menu. The Wizard will guide you through the earlier selections, and you can modify them before saving the Query.

Microsoft Query.

Alternatively, you can open the Microsoft Query Program (C:\Program Files\Microsoft Office\Office11\MSQRY32.EXE in MS-Access 2003) and open the saved Query (Refer earlier Post Access Live Data in Excel for Query File's default location) from the File Menu, edit the SQL String, and view the Output data in the Query Editor before saving the changes.

When you open the Query that you have created and saved earlier, the Source Data will be displayed in Datasheet View. Click on the SQL-labeled Toolbar Button or select SQL from the View menu.

You will find the SQL String like the sample given below:

SELECT Categories.CategoryID,
 Categories.CategoryName,
 Categories.Description,
 Categories.Picture
FROM `C:\Program Files\Microsoft Office\Office11\samples\Northwind`.Categories Categories

The normal SQL terminator character semicolon (;) is not present. The FROM Clause in the SQL is written differently without the use of an IN Clause, which we have seen in the MS-Access Query to Open Excel or dBase Tables directly using the Source Connect Str Property. The Categories Table Name is attached to the sample Database Path Name with a dot separator, and the Table Name is repeated with a space in between. The .mdb file extension for Northwind is also omitted from the database file name specification.

If you copy and paste the above SQL String into an MS Access Query and change it to Datasheet View, it will display the data correctly. No errors will be displayed, except that some Column headings may appear as Expr3, Expr4, and so on, if you have changed the Query in Design View first and then switched into Datasheet View.

Properties of Microsoft Query.

This is the time to learn the usage of two more Properties of MS Access Query.

  1. Copy the above SQL String into a new MS-Access Query SQL window.

  2. Select View -> Datasheet View to display Records from the Categories Table from the Northwind.mdb database.

  3. Select View -> Design View to change the Query Design View.

  4. The Table Object is already visible on the Query Design surface, but the Field Names are absent. Click on the title area of the Table to select it.

  5. Display the Property Sheet (View -> Properties. The Alias and Source Properties of the Query are displayed.

  6. The Table Name Categories are loaded in the Alias Property, and the Path Name of the NorthWind database appears in the Source Property without the .mdb extension.

  7. Change the Table Name appearing in the Alias Property to a different name, say myCategories.

  8. Add the .mdb extension at the end of the Path Name string in the Source Property.

The Table Name now appears as myCategories in the Title of the Table. Turn the Query into an SQL View. You can see that at the end of the SQL String, the reference to the Table name, Categories (which appeared twice earlier), has now changed to myCategories.

We must qualify each data field with the Table Name myCategories due to the Alias Name change. Change the SQL String as shown below to qualify each Field with the alias name. Enclose the Database Path Name in Square Brackets ([]) in place of the single quotes.

SELECT [myCategories].[CategoryID],
 [myCategories].[CategoryName],
 [myCategories].Description,
 [myCategories].Picture
FROM [d:\Program Files\Microsoft Office\Office\samples\Northwind.mdb].Categories AS myCategories;

The manual change is necessary because we are referencing an external data source, and there is no way MS Access can guess the name. If we are using a Table from within the Database or from a linked Table, then the Alias Name change will automatically take effect in all the fields. You can try this experiment with one of your own Tables from within the Database or with a linked Table.

Note: The Source Database and Source Connect Str Property Values are taken into the Query Syntax with an IN Clause to identify the external Application.

Alias Property is initially set with the Table Name and accepts changes to the Table Name through this Property.

Source Property accepts the external Database reference, either a direct Path Name or an ODBC Connection String, and the SQL Syntax is different in the FROM Clause of the Query definition.

Earlier Post Link References:

  1. Roundup Function in Excel in MS-Access
  2. Proper Function in Excel in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy-Paste Data From Excel to Access 2007
  7. Microsoft Excel-Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening an Excel Database Directly
  12. Create Excel, Word files from Access
Share:

MS-Access Live Data in Excel


MS-Access Live Data in Excel.

We have already explored several techniques for accessing and working with external data sources—such as Access tables, dBase files, and Excel worksheets—without permanently linking them. These included both VBA-based and query-based approaches.

However, we have not yet experimented with using an ODBC connection string in the SourceConnectStr property of a query to open external data files. While linking external data to Access is straightforward, we will later explore how to perform this linking dynamically through VBA.

Before diving into that, let’s look at something slightly different—a reversal of the usual “one-way traffic” of data flow from external sources into Access. Interestingly, the data flow isn’t truly one-way: we can also update external data directly from Access, whether or not those data sources are permanently linked.

When we use queries configured with SourceDatabase and SourceConnectStr properties to open external data, the resulting datasets are fully updatable. Any changes made to these records within Access are automatically reflected in their original parent applications.

Live MS-Access Data in an Excel Sheet

In this section, we will explore how to link live Microsoft Access data into Excel so that any updates made in Access are automatically reflected in Excel. In this setup, Access functions as the server application, while Excel acts as the client.

There is, however, one important distinction from our earlier methods: although you can edit the linked data in Excel, those changes will not be written back to Access.

So, what’s the purpose of having Access data in Excel? You can use it to create charts, perform calculations, or prepare analytical reports—especially if you’re more comfortable working in Excel. You can also create links (using Copy → Paste Special → Paste Link) to reference this live data in other parts of the workbook. This way, any updates in Access will automatically appear in your reports or charts within Excel, ensuring your information always stays current.

To bring Access data into Excel, we use Microsoft Query, which serves as the intermediary between the two applications. The Query Wizard will guide us through the necessary steps to connect Excel with the Access database.

For our example, we’ll use the Categories table from the Northwind.mdb sample database.

Step through the following procedure.

  1. Open a new MS Excel workbook.

  2. Select Cell A1 on Sheet1.

  3. Point to Import External Data in the Data Menu.

  4. Select New Database Query from the displayed menu.

    Now, the Microsoft Query Wizard opens up and displays a Dialog Box. It displays the Database Sources list in the Databases tab, which you can link to MS Excel. This is a combined list of items appearing in the ODBC Dialog Control User DSN, System DSN, and File DSN Tabs.

  5. Select the MS-Access Database* from the list and click OK.

  6. The Common Dialog Control opens up, allowing you to browse to the Location of the MS-Access Database and select it. Find the sample database C:\Program Files\Microsoft Office\Office11\Sample\Northwind.mdb (MS-Access 2003; you can drop 11 from Office11 in the location address for Access 2000), select it, and click OK.

  7. Select the Categories Table from the Available Tables and Columns in the Query Wizard and click on the > symbol to select all the Fields of the Categories Table into the Columns in your Query Control. If you don't need all the fields from the Source Table, then expand the Categories Table by clicking on the + symbol to display all the Fields and select only those you need and move them to the right side panel.

    Before you move the field to the right, you can preview the Field contents by clicking the Preview Now button below. Memo Field or OLE Object field contents cannot be previewed this way.

  8. After selecting the Fields, click Next. Here, you can define Filter conditions.

  9. Click Next to proceed to the Sort options.

  10. Click Next to move to the Finishing point.

    Here, we have the option to save the selected settings in a Microsoft Query (which is an external File) at the location C:\Documents and Settings\User\Application Data\Microsoft Queries\. If we need any changes in the data selection options, then we can open this saved file in Microsoft Query and edit the Query Definition in the SQL Window.

  11. See the Radio Button set on Return Data in Microsoft Office Excel and click Finish.

  12. In the next Dialog Control, you can select the Location on the Excel Sheet where you want to insert the data from Access. Since we have already selected Cell A1 as the target location in Step 2 above, this will appear as the default location in the control; click OK without change.

The records from the Categories Table will be inserted in the Excel Worksheet, starting from the range address A1.

It was a long journey from Access to Excel. Bringing Excel data into Access needs only two property changes in an MS Access query, and now you know how simple it is.

Refreshing Updates from Access Table.

Now that we have successfully brought Access data into Excel, let’s perform a few simple experiments to confirm that it is indeed live data—directly linked to the Access database. We’ll also observe how any changes made in Access are automatically reflected in Excel, demonstrating the dynamic connection between the two applications.

There are two methods to refresh Access Data in Excel: Manual and Automatic.

Keep the Northwind.mdb sample database open so that we can make changes in the linked table in Excel or in Access and check the results of the change in both Applications.

  1. Open the Categories Table of the Northwind.mdb Database.

  2. Add Crabs and Lobsters in the Description field of the last record. Or add a new record with some Category Name and Description.

  3. Minimize MS Access and display the Excel Window, and check whether the change has taken place immediately in the linked data in Excel. You may not find any change on the Excel side. We have to refresh the data in Excel to reflect the changes.

  4. Click anywhere within the data Area.

  5. Select Refresh Data from the Data Menu.

    Now, any changes you make in Access will automatically be updated on the Excel side as well. Moreover, you can configure Excel to refresh the linked data automatically at regular intervals, eliminating the need to perform manual updates.

  6. Right-click anywhere within the linked table in Excel and select Data Range Properties from the shortcut menu.

  7. In the dialog box that appears, you will find several options to manage the linked data, including the name of the query that retrieves data from Access into Excel. Under the Refresh Control section, select the Refresh every option and set the interval to 1 minute. This allows you to observe the automatic refresh in action without waiting too long.

  8. Next, switch to the Access window and either undo the earlier changes made to the Categories table or make new edits that will be easily noticeable in Excel once the data refreshes.

  9. Return to Excel and wait for the refresh to occur. You should soon see the updates reflected in the worksheet—Excel will continue to refresh the data automatically at one-minute intervals.

If you have made any changes to the data on the Excel side, those modifications will be lost during the refresh process.

When you close and reopen the Excel workbook, a prompt will appear asking whether Excel should automatically refresh the linked data. You can choose to enable or disable this feature according to your preference.
Share:

Database Connection String Properties

Database Connection String Properties.

Opening external data sources such as dBase files, Excel sheets, or tables from another MS Access database directly through VBA code is just one of the available options. For those who are not comfortable working with VBA, a better alternative allows you to access external data without permanently linking it to your Access database.

In either approach, one thing remains essential: you must know how to correctly reference different external data sources using the appropriate Source Database Path and Connection String values. Fortunately, these methods are quite straightforward to learn.

While understanding the syntax for ODBC (Open Database Connectivity) connection strings can be slightly challenging, there are some helpful shortcut techniques to determine them. However, we will set aside the ODBC discussion for now and revisit it later with a relevant example.

As demonstrated earlier, we can display values from Excel cells or ranges directly on MS Access form controls.

In the previous examples on opening Access tables, dBase tables, and Excel tables directly through VBA, you may have considered copying the SQL strings from the VBA code into queries and testing them there. If you haven’t done so yet, now is a good time to try—it’s a great way to understand how they work and to explore a few important details about their usage.

Open Recordset in Select Query, from External Access Database

Let us try to open an MS Access table from another Database directly in a Select Query.

  1. Open one of your Databases or create a new one.

  2. Select the Query Tab and Click the New Button on the Database Menu. Select the Design View from the displayed Options and click Close without selecting any Table from the list.

  3. Click on the SQL Toolbar Button or select SQL View from the View Menu.

  4. Copy and Paste the following SQL String in the SQL Editing Window, and Save the Query with the Name EmployeesQ.

    SELECT Employees.* 
    FROM Employees IN 'C:\Program Files\MicrosoftOffice\Office\samples\Northwind.mdb';

    Note: If you are using MS-Access 2003, then change the Path to . . .\Office11\Samples\.

  5. Open the Query in Datasheet View (View -> Datasheet View) to display the Employees Table contents from the Sample Database Northwind.mdb.

In the SQL String, the IN Clause points to the correct database path, and the entire Path Name is put in quotes and ends with a semicolon, indicating the end of the SQL String, which is applicable for all Queries.

A Different and Simple Method.

There’s another way to accomplish this. The first part of the statement can be written directly in the SQL window, while the IN clause can be added separately in the Source Database and Source Connection String properties of the query. This approach eliminates the need to remember where to place the word IN, or where to insert opening and closing quotation marks, freeing you from such syntax concerns.

  1. Create a New Query and open the SQL editing window following Steps 1 to 3 explained above.

  2. Write the SQL string SELECT Employees.* FROM Employees;

  3. Select Design View from the View Menu to change the Query from SQL View to Design View. We are now in the normal Query Design View. You will find the Employees Table object appearing in the Query Design without any Field Names showing in it.

  4. Select Properties from the View Menu to display the Property Sheet of the Query.

  5. Click on an empty area of the Query surface, to the right of the Table Name, to display the Query level Property Sheet correctly.

  6. There are two properties on the Property Sheet that we are interested in.

    • Source Database
    • Source Connect Str

    Here, we will be using only the Source Database Property for the external MS Access Table.

  7. Enter the following Path Name in the Source Database Property, overwriting the text (current).

    C:\Program Files\Microsoft Office\Office\samples\Northwind.mdb

    Or with the change explained above for MS-Access 2003 cases.

  8. Select Datasheet View from the View Menu.

You will now see the same result as the first Select Query we tried. If you change the Query into its SQL View and inspect the SQL String, you can see that the IN Clause is formed using the Source Database property Value.

Source Connect Str for dBase and Excel.

You can use the same method for a dBase Table and an Excel Table (Named Range). In these cases, we need to use the Source Connect Str Property.

Example: opening the dBase Table directly.

Table Name: Customer.dbf

SQL String: SELECT Customer.* FROM Customer;

Source Database Property Value = C:\mydBase

Source Connect Str Property Value = DBASE IV; (check the semicolon at the end)

Replace the Customer table name and the Path C:\mydBase location address with your own dBase File Name and Folder name, where the dBase Table is located.

Example: opening an Excel Table (Named Range) directly.

Table Name: Categories

SQL String: SELECT Categories.* FROM Categories;

Source Database Property Value = C:\My Documents\Products.xls

Source Connect Str Property Value = Excel 5.0;

(note the semicolon at the end)

Replace the Categories table name and the Path C:\My Documents\Products.xls Excel file with your own.

NB: You must first define the Name Categories in the Excel Table Range using Insert -> Name -> Define before attempting to use the Name Categories in MS-Access Queries.

Next: MS-Access Live data in Excel

Earlier Post Link References:

Share:

Opening Excel Database directly

Opening an Excel Database directly.

In the world of Personal Computers, many applications emerged and disappeared. One of the very popular applications was WordStar (Word Processor), which used the operating systems CP/M-80 (Control Program for Microcomputers) and MS-DOS (Disk Operating System) till 1992. There were dedicated Word Processing Machines in those days, using WordStar and competing Software WordPerfect. 

The first spreadsheet program, VisiCalc, was released in 1979 and made a groundbreaking impact. It soon inspired several successors—SuperCalc, Multiplan, Lotus 1-2-3 (1983), and eventually Microsoft Excel (1985)—each adding more power and functionality than the original VisiCalc. (Source: Wikipedia)

Like Microsoft Access, Microsoft Excel also includes powerful automation capabilities that make spreadsheet-based computing both flexible and engaging.

Spreadsheet programs are designed for analytical tasks that involve a chain of calculations, with all relevant data visible on the sheet. A small change made at the beginning of a calculation can trigger a cascading effect through dependent cells, instantly updating the final results. This makes Excel an invaluable tool for “what-if” analysis. And when it comes to creating graphical charts, Microsoft Excel remains the first name that comes to mind.

Excel Table

Although Excel includes limited database-like features, such as built-in functions, filters, and sorting capabilities, it can still be used effectively for structured data management. This brings us to our next example—creating a table in Excel that can be read from or updated by Microsoft Access.

While Excel provides the tools needed to follow general database principles when creating and maintaining a table, these rules are often overlooked. Users are free to design their worksheets in any manner, even mixing regular data and database-like tables side by side on the same sheet.

In contrast, Access enforces strict data integrity rules—for example, text cannot be entered into numeric fields, field names must be unique, and data cannot exceed defined field sizes. The same principles technically apply in Excel, but violations often go unnoticed because Excel doesn’t always flag them. As a result, the worksheet may not function as intended when used as a data source.

Moreover, not all Access data types exist in Excel—for instance, the True/False field type in Access has no direct equivalent, although Boolean values like TRUE and FALSE are still valid entries in Excel cells.

Before we create a database-style table in Excel and open it directly in Access (as we did with a dBase file), let’s explore how to set data validation rules in Excel to restrict cell entries. You may be surprised by how powerful these validation features can be.

Validation Settings.

Example: Accept only values between 25 and 100 in a Cell or Cells.

  1. Open Excel and select a Cell in Sheet1.

  2. Select Data -> Validation ...  -> Settings.

  3. Select Whole Number in the Allow control.

  4. Enter 25 in the Minimum Control and 100 in the Maximum Control.

  5. Select the Input Message Tab. Enter Age in the Title Control and type Enter Value between 25 and 100 in the Input Message.

  6. Select the Error Alert Tab and type Value Error in the Title Control.

  7. Type Valid Value between 25 and 100 in the Error Message Control and click OK to close it.

Try entering a value less than 25 or greater than 100 in this cell, and it will display the Error message that you have set up in the Validation Control.

You can apply the same rules quickly to other cells. Copy the Cell, highlight the Range of Target Cells, and select Edit -> Paste Special -> Validation. If you paste it over existing data, it will not validate the field contents if the wrong value is already present in the Cell. The validation check is performed only when you manually key in values.

Following the same procedure, try setting up a validation rule in Excel to accept 15 characters or fewer in a cell. Try entering 16 characters or more into that Cell.

When planning to create a database in Excel, begin by defining short, meaningful headings in the top row—these will serve as your field names. Next, apply data entry rules (as explained earlier) to each column so that only valid values can be entered. Excel also provides a built-in Data Entry and Search Form, similar to the one available in Microsoft Access.

If you already have a data table in Excel, simply click anywhere within the table and select Form from the Data menu. This will open a Data Entry/Search Form. By clicking the Criteria button, you can switch it into search mode, where you can enter specific criteria in any field to locate a record.

You can experiment with this feature after we create an Excel table, which we’ll later open directly in MS Access through a VBA program.

Preparing for a Trial Run.

  1. Open Microsoft Excel (if it is already closed).

  2. Open the NorthWind.mdb sample database. Check the link Saving Data on Forms not in Table for location references if you don't know where this file can be found.

  3. Open the Categories Table in Datasheet View.

  4. Right-click on the top left corner of the Datasheet View and select Copy from the shortcut menu.

  5. Click on the Excel Icon on the Taskbar to open it and select Cell A1.

  6. Select Paste from the Edit Menu.

  7. While the highlighting is still on the pasted Table, select Insert -> Name -> Define and type Categories in the Names in Workbook control; click the OK button to close it.

  8. Save the Workbook with the name: C:\My Documents\myData.Xls, and close Microsoft Excel and close the Northwind.mdb sample Database.

  9. Open any one of your Databases or create a new one.

  10. Copy and paste the following code into the Global VBA Code Module of your Database and keep the Module open. You may save the Module by selecting the Save Toolbar Button or with the File -> Save option.

    Public Sub OpenDirectExcel()
    '-----------------------------------------------------
    'Open Excel Table directly
    'Author : a.p.r. pillai
    'URL    : www.msaccesstips.com
    'All Rights(c) Reserved by msaccesstips.com
    '-----------------------------------------------------
    Dim db As Database, rst As Recordset
    Dim strSql As String, i As Integer
    Dim msg As String
    
    strSql = "SELECT Categories.* FROM Categories IN 'C:\My Documents\myData.xls'[Excel 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 & ![Category Name] & vbCr
       If ![Category Name] = "Confections" Then
          .Edit
          ![Category Name] = "Chocolates"
          .Update
       End If
       i = i + 1
       .MoveNext
    Loop
    .Close
    End With
    
    MsgBox msg, , "Product Categories"
    
    Set rst = Nothing
    Set db = Nothing
    
    End Sub
    
  11. Click in the Code and press F5 to run it. Displays the Product Category Names of the first five Records from the Categories Table in C:\My Documents\myData.xls in a Message Box.

Note: In the VBA Code, we have tested the Category Names Field for the value Confectionaries, and updated the Value Chocolates back into the Excel Cell, overwriting the word Confectionaries.

Check the SQL Syntax in the Code that pulls the data directly from the Named Range Categories in the C:\My Documents\myData.xls file.

  1. Microsoft Excel and Automation
  2. Microsoft Excel and Automation-2

Next: Database Connection String Properties

Earlier Post Link References:

  1. Roundup Function
    of Excel in MS-Access
  2. Proper Function of Excel in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy-Paste Data From Excel to Access 2007
  7. Microsoft Excel Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening an Excel Database Directly
  12. Create an Excel Word File from Access
Share:

Display Excel Value Directly on Form

Display Excel Value Directly on Form - MS Access 2003.

In the earlier post, Opening dBase Files Directly, we learned how to open and work with dBase files in MS Access using VBA. However, there are several alternative methods—other than linking—to handle dBase files within Access. We’ll explore those options in detail later.

This post, however, was originally meant to demonstrate how to open an Excel-based data table directly and work with it in VBA. We’ll cover that in the next section. But before diving into that, let’s take a short detour to try out some simple yet fascinating Excel tricks.

I say “simple” because you won’t need to wrestle with any complex VBA code this time. And I know you’ll appreciate that little break from my so-called spaghetti code!

As the title suggests, we’re going to explore how to display values from an Excel worksheet directly on Microsoft Access forms—no heavy coding required.

The Demo Run Preparation

  1. Open Microsoft Excel.

  2. Enter your name in cell A1 on Sheet1, then minimize Excel—but don’t close it. You may save the workbook with a suitable name. Keep in mind that if the AutoSave feature is turned on, Excel may prompt you to save your changes.

  3. Open any one of your Microsoft Access Databases or create a new one.

  4. Open a New Form in Design View.

  5. Select the Text Box Tool from the Toolbox and draw a Text Box on the Detail Section of the Form.

  6. Click on the Text Box and display the Property Sheet (View -> Properties).

  7. Write the following expression in the Control Source Property of the Text Box:

    =DDE("Excel","Sheet1","R1C1")

  8. Save the Form with the name of your choice.

  9. Open the Form in Normal View. You will see your Name written in an Excel Cell appearing in the Text Box on the Form.

    The DDE() Function stands for Dynamic Data Exchange. The first two Parameters are the Excel Application and the worksheet name Sheet1, and the third one is the Cell Reference where your name is written in R1C1 (Row-1 Column-1 or Cell A1). The cell reference must be used in this way rather than the A1 style.

    Do the following if not successful.

    But you may end up with nothing showing in the TextBox. In that case, you have to see if a particular Option is set correctly on the General Tab of Options in the Excel Tools Menu.

  10. Click on the Excel icon on the Taskbar to open it. Click on Tools -> Options, and select the General Tab.

  11. Remove the check mark (if it is set) from the Ignore Other Applications option in the Settings Options.

  12. Minimize Excel, close the MS Access Form, and open it again. Now you must see your name in the Excel Cell on the Form. Don't close the Form.

  13. Maximize Excel, make some changes to the Name, and minimize again. The change may not reflect immediately on the Form. You can update the Form value manually without the closing and opening steps.

  14. While the Access Form is in Normal View, select OLE/DDE Links from the Edit Menu.

  15. The Links Dialog Box will open up. Select DDE Links in the Links Group control. The Links list will appear below. Select the Link and click on the Update Now Command Button. Now the change on the Worksheet will reflect the Form Value.

Microsoft Access also includes option settings similar to those in Excel. Generally, instead of manually refreshing changes—as we did earlier—the updates should occur automatically at fixed intervals according to the settings under Tools → Options in Microsoft Access. However, in my experience, this feature hasn’t worked reliably on my system so far.

Select Tools → Options → Advanced tab. Ensure that the Enable DDE Refresh option is checked if it is not already enabled. In this section, you can also view the default settings for automatic refreshing of Dynamic Data Exchange (DDE) and ODBC links — including the number of retry attempts and the wait time before Microsoft Access tries again in case of a failure.

Display Value in Combo Box and Option Group.

You can display Values from Excel in two more Access Controls: ComboBoxes and an Options Group Control. See the sample image given below.


The Combo Box Method

  1. Minimize Access and Maximize Excel.

  2. Enter a few Names of people, books, or anything else in Cells A9 to A17.

  3. Enter Value 2 in Cell C1 and minimize the Excel Application Window.

  4. Maximize MS Access and open the Form in Design View.

  5. Disable the Control Wizards Button on the Toolbox. Select the Combo Box Tool and draw a Combo Box Control on the form so that it looks like a List Box. See the sample image given above.

  6. Display the Property Sheet and write the expression

    =DDE("Excel","Sheet1","R9C1:R17C1")

    In the Control Source Property of the Combo Box.

    You may give a Name to the Range: R9C1:R17C1 and use that Name in the expression, replacing the Range Address. To name the Excel Cell Range, highlight the Range, select Insert -> Name -> Define, and type the name, say List, in the Names in Workbook control. Replace the third Parameter R9C1:R17C1 with the Range Name List in the DDE Function.

  7. Open the Form in Normal View. The Names from the Excel Range will appear in the Combo Box.

Note: You cannot select any of these values and insert them into the Text Box portion of the Combo Box and use it in a data field.

The Option-Group Option.

We will try one more example with the Options Group Control.

  1. Turn On the Control Wizard in the Toolbox. Select the Option Group Tool from the Toolbox and Draw an Option Group Control on the Form. Refer to the example given above.

  2. Type three Labels in the Wizard: Data View, Print Preview, and Print, or anything else you prefer, on the control, and click Finish.

  3. Click on the outer frame of the Options Group and display the Property Sheet (View -> Properties).

  4. Write the following expression in the Control Source Property:

=DDE("Excel","Sheet1","R1C3"

The selection of items on the Options Group will be based on the value given in Excel Cell C1. Now the value in Cell C1 is 2. The second item in the Options group will now show as selected. Change the Value in Cell C1 to 3 and refresh the Form as explained above; the option will change to 3.

Note: If the Excel Application is not active when you open the Form with the DDE() Function, then Access will show the following Error Message:

"You tried to open a form or report that includes a DDE or DDESend function in a calculated control that specifies an OLE server application."

"Do you want to start the application in Excel?"

If you respond with Yes, then the Excel Application will be started with Blank Sheets. You must open the Excel Workbook that provides information for the DDE() function manually, and display the values in the Access Form.

Next: Opening an Excel Database directly.

  1. Roundup Function of Excel in MS-Access
  2. Proper Function of Excel in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy-Paste Data From Excel to Access 2007
  7. Microsoft Excel Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening an Excel Database Directly
  12. Create an Excel Word File from Access
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 External Links Queries Array Class Module msaccess reports Accesstips msaccess tips WithEvents Downloads Objects Menus and Toolbars MsaccessLinks Process Controls Art Work Collection Object Property msaccess How Tos Combo Boxes ListView Control Query VBA msaccessQuery Calculation Dictionary Object 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 Recordset Top Values Variables msaccess email progressmeter Access2007 Copy Excel Expression Fields Join Methods Microsoft Numbering System RaiseEvent Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup Wrapper Classes 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 Export 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