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

Budgeting and Control

Budgeting and Control.

The local Charity Organization for Children allocates funds for disbursement under various categories to eligible individuals or entities. The Accounts Section oversees these disbursement activities and ensures that the total payments made under each category do not exceed the allocated budget.

We have been asked to develop a computerized system to monitor the payment activity and verify that the cumulative value of all payments for a given category remains within the approved budget limit.

Below is a sample screen used for recording payment details:

As shown in the screen above, a Budget Amount of $10,000 has been allocated to the Poor Children’s Education Fund. This amount is distributed to eligible individuals or deserving institutions after careful evaluation of their cases. The payment records are entered in the datasheet subform below. Both the Main Form and the Subform are linked through the Category Code, an AutoNumber field in the main table.

When a new record is entered in the subform with a payment amount, the program calculates the total of all payment records, including the current entry, and compares it against the budget amount on the main form. If the total payment amount exceeds the allocated budget, an error message is displayed. In such cases, the program automatically deducts the excess amount from the current payment value.

After this adjustment, the focus is set to the Amount field, allowing the User to review the correction and take appropriate action if necessary.

In this example, users are not restricted from modifying the Budget Amount. However, the field can be locked immediately after a new main record is created for the budget value. If authorized modifications are required at a later stage, special access rights can be granted to designated Users through Microsoft Access Security features. For the time being, let us keep aside the security aspect; let us take a closer look at the design and implementation of the datasheet subform and the associated procedures.

An image of the Payment Record Sub-Form Data Sheet Design View is given below:


A TextBox with an Active Record not yet saved.

We created a Text Box in the Subform Footer Section with an expression to calculate the total of all payment records for the current category, excluding the current new record. This happens because the Sum() function does not include the new record value until it is saved in the table.

For example, the Text Box expression:

=Sum([Amt])

will correctly total all saved records. Although this control is not visible in Datasheet View, it can still be referenced in VBA procedures. (For additional techniques with Datasheet Forms, see the article Event Trapping and Summary on Datasheet.)

To include the value of the current (unsaved) record in the total, we can read it directly from the field (Me![Amt]) and add it to the result of the Sum() function. This gives us the Total of all disbursement records, including the current entry.

We can then compare this calculated total against the Budget Amount on the main form before accepting the new record. If the total exceeds the budget, the program can alert the user. This ensures that no payment entry pushes the cumulative disbursement beyond the allocated amount.

The Sub-Form Module Code.

The VBA Program Code written in the Sub-Form Module is given below:

Option Compare Database
Option Explicit
'Gobal declarations
Dim Disbursedtotal As Currency, BudgetAmount As Currency, BalanceAmt As Currency
Dim errFlag As Boolean, oldvalue As Currency

Private Sub Amt_GotFocus()
'Me!TAmt is Form Footer Total except the new record value
Disbursedtotal = Nz(Me!TAMT, 0)
BudgetAmount = Me.Parent!TotalAmount
oldvalue = Me![Amt]
End Sub

Private Sub Amt_LostFocus()
Dim current_amt As Currency, msg As String, button As Long

On Error GoTo Amt_LostFocus_Err
Me.Refresh
'add current record value to total and cross-check
'with main form amount, if the transactions exceed
'then trigger error and set the focus back to the
'field so that corrections can be done
current_amt = Disbursedtotal + Nz(Me!Amt, 0)
BalanceAmt = BudgetAmount - current_amt
errFlag = False
If BalanceAmt < 0 And oldvalue = 0 Then
    errFlag = True
    button = 1
        GoSub DisplayMsg
ElseIf oldvalue > 0 Then
    current_amt = (Disbursedtotal - oldvalue) + Nz(Me!Amt, 0)
    BalanceAmt = BudgetAmount - current_amt
    If BalanceAmt < 0 Then
        errFlag = True
        button = 1
          GoSub DisplayMsg
    End If
Else
    Me.Parent![Status] = 1
End If

Amt_LostFocus_Exit:
Exit Sub

DisplayMsg:
    msg = "Total Approved Amt.: " & BudgetAmount & vbCr & vbCr & "Payments Total: " & current_amt & vbCr & vbCr & "Payment Exceeds by : " & Abs(BalanceAmt)
    MsgBox msg, vbOKOnly, "Amt_LostFocus()"
Return


Amt_LostFocus_Err:
MsgBox Err.Description, , "Amt_LostFocus()"
Resume Amt_LostFocus_Exit
End Sub

Private Sub Form_Current()
Dim budget As Currency, payments As Currency

On Error Resume Next

budget = Me.Parent.TotalAmount.Value

payments = Nz(Me![TAMT], 0)

If payments = budget Then
 Me.AllowAdditions = False
Else
  Me.AllowAdditions = True
End If

End Sub

Private Sub Remarks_GotFocus()
If errFlag Then
  errFlag = False
  Me![Amt] = Me![Amt] + BalanceAmt
  BalanceAmt = 0
  Me.Parent![Status] = 2
  Me.Amt.SetFocus
End If

End Sub

Performing Validation Checks.

During data entry in the Payment Subform, if the cumulative value of all payment records reaches the allocated Budget Amount, the form will prevent adding any more payment records. However, existing payment records may still be opened and edited.

Similarly, when any Budget Category record becomes current on the Main Form, the program checks whether the total of its related payment records already equals the budgeted amount. If this condition is met, the Payment Subform is locked against new entries, but existing payment records remain editable.

The following VBA procedure, written in the Main Form’s module, enforces this rule and ensures that users cannot enter payment records once the budget is fully utilized:

Main Form Module Code.

Option Compare Database

Private Sub cmdClose_Click()
DoCmd.Close
End Sub

Private Sub Form_Load()
DoCmd.Restore
End Sub

Private Sub Form_Current()
Dim budget As Currency, payments As Currency
Dim frm As Form
On Error Resume Next

Set frm = Me.Transactions.Form
budget = Me!TotalAmount
payments = Nz(frm![TAMT], 0)

If payments = budget Then
 frm.AllowAdditions = False
Else
  frm.AllowAdditions = True
End If

End Sub

Demo Database Download.

Click the following link to download a Demonstration Database with the above Code.


Download Demo BudgetDemo.zip


Share:

Change Secure DB to Unsecured

Change Secure DB to Unsecured.

It is generally uncommon to convert a secured database (implemented using Microsoft Access Security) into an unsecured one. However, this step may become necessary when you want to deploy or share a database in an environment that does not use security.

The first step in removing security from a database is to change the ownership of the database objects. By default, the User who creates the database is its Owner. The owner of an object has full access rights to it and can also assign permissions to other Users or Groups. Additionally, members of the Admins group possess these privileges.

Points to remember:

  1. The User who attempts to convert the Database must have at least Read Permission to all Objects of the Database.

  2. The Hidden Objects, if any, cannot be transferred into the target Database.

The Conversion Process.

The conversion process is simple and needs only a few steps.

  1. Create a new Database.

  2. Select File --> Get External Data --> Import.

  3. Browse to the location of the Database you are trying to convert, and open it.

  4. Select the Tables tab, and click the Select All Command Button to select all Tables to import.

  5. Repeat this method for all Queries, Forms, Reports, Macros, and Modules.

  6. If your Database has Custom Menus and Toolbars, then click on Options.

  7. Select the Menus and Toolbars option.

  8. Click OK to import all Objects (except the hidden objects) into the new Database.

At this stage, the access privileges of all objects in the new database are reset to their defaults. By default, every database user is a member of the Users group, and therefore has full access rights to all objects. This includes permissions to Open/Run, Read Design, Modify Design, and Administer permissions.

However, if you intend to share this unsecured database over a network, a few additional changes are required to enable concurrent use. Without these adjustments, the database will be limited to single-user access, preventing concurrent use. 

Changes for Multi-User Environment.

  1. Select Tools --> Options --> Advanced.

  2. Select Shared under the Default Open Mode Options Group.

  3. Select Edited Record under the Default Record Locking Options Group.  Open Database using Record Level Locking Option is already in the selected state.

  4. Click OK to close the Dialog Box.

  5. Select Tools --> Security --> User and Group Permissions.

  6. Select the Admin User Name under the User/Group Name List. 

    Why select Admin User Account? Because in an unsecured environment, it is a member of the Admins Group and logged in silently when no password is set.  MS Access will not prompt for User ID and Password.

  7. Select the Database Object in the Object Type Control.

  8. Unselect the Open Exclusive Option.

  9. Click OK to close the Dialog Box.

Now, you have a new Database with no Security settings.  The old database will remain unchanged.

Technorati Tags:

  1. Microsoft Access Security
  2. Convert MS-Access Old Versions
  3. Convert Old Version Workgroup File
  4. Share Previous Version Database

Share:

Date and Time Values

Date and Time Values.

The Date/Time Field in MS Access can store a date alone or a date and Time together. When you enter a date value (for example, 14/07/2010), Access actually stores it as a whole number: 40373. This number is the day count since 30/12/1899, where day 1 corresponds to 31/12/1899.

You can verify this by typing the expression Format(1, "dd/mm/yyyy") in the Immediate (Debug) window. To open it, press Alt+F11 to display the VBA editor, then press Ctrl+G. Pressing the Enter Key will display the result 31/12/1899.

Similarly, time values are stored as decimal fractions of a day. For example, midnight corresponds to 0.0, while 12:00 noon corresponds to 0.5. When combined, a date and time are held in memory as a single numeric value. Thus, 14/07/2010 at 12:00 noon is stored as 40373.5.

When calculating time differences across midnight, Access treats midnight as 24.00 rather than 0.00 to ensure accurate results for times before midnight.

Type ? Format(40373.5,"dd/mm/yyyy hh:nn:ss") and press the Enter Key.

Result:  14/07/2010 12:00:00

It is interesting to explore how 0.5 becomes 12:00:00 noon or how the System maintains Date and Time internally.

We know we have 24 Hours in a Day, or 24 x 60 = 1440 minutes in a Day, or 24 x 60 x 60 = 86400 Seconds in a Day.

Time Calculations.

That is, 1 Second = 1 Day/86400 Seconds = 0.000011574074074074 Day (we can take it rounded as 0.0000115741).  The end value of 074 is infinite. Again, 1 second is = 1000 Milliseconds.

From midnight onward, the time value increases by 0.0000115741 day per second. At 23:59:59 (one second before midnight), the stored value is approximately 0.9999906659 (representing 86,399 seconds). After one more second, the day value increases by 1, so the timestamp becomes 40374.0, representing 15/07/2010 at 00:00:00.

Each second is further subdivided into milliseconds, which can be accessed using the built-in Timer function.

For example, type the following direct command in the Debug Window:

? Timer

You will get output similar to the example below, depending on when you try this.

Result in Seconds: 68473.81

The .81 part is the time in milliseconds, and 68473 is the current time in seconds.

If you want to see this value in the Current Time of the Day format, type the following expression in the Debug Window and press the Enter key:

? format(68473.81/86400,"hh:nn:ss")

OR

? format(68473.81*0.0000115741,"hh:nn:ss")

The Value 68473.81 Seconds multiplied by 0.0000115741 gives the daytime value.

Result: 19:01:14

Using the Timer Function.

You can use the Timer() Function to build a delay loop in a Program. The code below delays the action by 5 seconds in program execution.

Public Function myFunction()
.
.
.
t = Timer
Do While Timer < t + 5 

  DoEvents

Loop
.
.
.
End Function

In the sample program shown earlier, the action is delayed by 5 seconds before the next statement execution after the loop.

We can retrieve the current system date and time using the built-in Now() function, while the Date() Function returns only the current system date.

When designing a table, you can set the Default Value property of a Date/Time field to either Date() or Now(). This automatically inserts the current date or the current date and time stamp, respectively, whenever a new record is added.

Now that we understand the basics of how time values are maintained internally, let’s look at some examples of the normal time-value conversions involving hours, minutes, and seconds.

Always use date and time values together when calculating time differences. If you are designing a table and performing time-based calculations, store both the date and time in a single Date/Time field, rather than in separate fields. This is especially important when the time period spans more than one day—for example, if work begins at 20:00 and ends at 04:00 the following day.

Now, consider a case where the values are stored separately:

  • Date: 25/10/2020

  • Time: 5 hours, 7 minutes, 15 seconds

How can these be combined and converted into the correct internal storage format that represents both the date and time together?

Date and Time Converting to store in the Date/Time Field.

The Date Number 25/10/2020 is 44129 is the internal value.

To cross-check whether the number is correct or not, type the following expression in the VBA Debug window and print the result:

? format(#25/10/2020#,"0")

Result: 44129

Now, all the time values (5 Hours, 7 Minutes, and 15 Seconds) we need to convert into seconds first, then add them all together and divide the result by 86400 or (24*60*60) to get the internal time format suitable to add to the date number so that the date and time value stays together in the Date/Time Field.

Now, let us do that as follows:

d_date = #25/10/2020# hrs = 5 min = 7 sec = 15 h_seconds = hrs * 60 * 60 m_seconds = min * 60 Total = h_seconds + m_seconds + sec ? Total Result: 18435 'seconds 'Convert to Time Value timVal = Total/86400 OR timval = Total/(24*60*60) ? timval Result: 0.213368055555556 'Add TimeValue to d_date d_date = d_date + timval

'Print the value of d_date in Date/time format ? format(d_date,"dd/mm/yyyy hh:nn:ss") Result: 25/10/2020 05:07:15

You may convert the Hours, Minutes, and Seconds into Time Value format in a single expression:

timval = (((hrs*3600)+(min*60)+sec)/86400)

d_date = d_date + timval

OR

d_date = d_date + (((hrs*3600)+(min*60)+sec)/86400)

Date/Time Values change to Date, Hours, Minutes, and Seconds.

How do we separate them again into Date, Hours, Minutes, and Seconds, if we want them in that way again, from the Date/Time Values?

'The Date/Time Value
'we have the date+time in:
d_date = d_date + timval

'get date value separate
dt = int(d_date)

timval = d_date - dt

'get hours
hrs = int(timval*24)

'subtract hrs value from time value
timval = timval - ((hrs*3600)/86400)

'get Minutes
min = int(timval * (24*60))

'subtract Minutes from time value
timval = timval-(min*60/86400)

'get seconds
s = int(timval*86400+0.1)

The +0.1 added for the correction of the rounding Error of the actual value of

The Simple Recommended Method.

If you want to do it differently, here it is:

d = 1/86400 :'1 second value = in day value internaly H = 5 M = 7 S = 15 t = ((H*3600)+(M*60)+S)/86400

? t

0.213368055555556

TotalSeconds = t/d ? TotalSeconds 18435 hr = int(TotalSeconds/3600) ? hr 5

bal = TotalSeconds-(hr*3600) ? bal 435

mi = int(bal/60) ? mi 7

se = bal-(mi*60) ? s 15

?

? format(t,"hh:nn:ss")
05:07:15

You can follow any method you feel comfortable working with, and I recommend the last one.

Earlier Post Link References:

Share:

Limit to List Combo Box

Limit to List Combo Box.

Combo Boxes in tables and forms are used to quickly insert frequently used values into data fields. The source data for a combo box can come from a table, a query, or a value list. To use it, the User clicks the drop-down arrow to display the available options and selects the required value. Alternatively, the user can also type in values directly into the combo box control.

However, one important property setting determines how the combo box behaves:

  • The first setting restricts the user to selecting only from the existing list and prevents invalid values in the target field.

  • Limit to List = Yes

  • On Not in List = [Event Procedure]

When the Limit to List property is set to Yes, you can only select or type values that already exist in the combo box list. Any manually entered values that are not in the list will be rejected. To use a new value, it must first be added to the source table (or query/value list) that supplies data to the combo box.

Example:

Suppose you have a table containing a list of fruits and have only two items: Apple and Cherry. This list is used as the source for a combo box on a Sales Form. If the Limit to List property is set to Yes, you cannot type Orange directly into the field. Instead, you must first add Orange to the fruit table; only then will it appear as a valid option in the combo box.

The On-Not-in-List Event.

When the On Not in List Property is set to an Event Procedure, it is executed when the user enters a new value (Orange) manually into the Control-Source Field of the ComboBox. We can write code in the Event Procedure to add the new value to the ComboBox Source List (after the User approves) and update the ComboBox on the Form.

This method saves the time that would otherwise be spent opening the combo box’s source table and manually adding new items. In addition, values added directly to the source table do not refresh the combo box.

Let us try this using the above example items as Source Data.

Combo Box Row Source Table.

  1. Create a new Table with a single Field Name: Fruit and select the Data Type Text.

  2. Save the Table Structure and name it Fruitlist.

  3. Open the Table in Datasheet View and key in Apple and Cherry as two records.

  4. Close and save the Table with the records.

  5. Create another table with the following Structure:

    Table Structure
    Field Name Data Type Size
    ID AutoNumber
    Description Text 50
    Quantity Numeric Long Integer
    UnitPrice Numeric Double
  6. Before saving the Structure, click on the second Field Data Type (Text) Column to select it.

  7. Click on the Lookup Tab on the Property Sheet below.


    Combo Box Property Settings.

  8. Select the Display Control Property and select Combo Box from the drop-down control.

  9. The Row Source Type Property Value will be Table/Query; if it is not, then select it from the drop-down control.

  10. Click on the drop-down control of the Row Source Property and select the Table Fruit list from the displayed list of Tables.

  11. Change the Column Width Property and List Width Property Values to 1".

  12. Change the Limit to List Property Value to Yes.

  13. Save the Table Structure with the name Sales.

  14. Open the Table in Datasheet View and add a new record with Apple, 100, and 1.5 in Description, Quantity, and UnitPrice Fields, respectively.

  15. Close and save the Table with the record.

  16. Select the Sales Table, select Form from the Insert Menu.

  17. Create a Form using the Form Wizard in Column Format and save it named Sales.

    Testing Settings.

  18. Open the Sales Form in the normal view.

    Since we have added the Combo Box to the Table Structure, it already appears on the form.

  19. Press Ctrl++ (or click on the New Record control on the Record Navigation control) to add a new blank record on the Form.

  20. Click the drop-down control of the Combo Box, and you will find the list of fruits: Apple and Cherry there.

  21. But you key in Orange into the Description field and press Enter.

    You will be greeted with the following error message:

    If you want to enter the value Orange on the Form, you must add that item to the Fruit List source Table first.

  22. To add a new item, open the Fruit List table, enter Orange as a new record, and then close the table.

However, this action will not automatically refresh the Combobox contents to include Orange. To see the updated value, you must either close and reopen the Sales form or add a command button to the form and write code that requeries the combo box contents.

What we did manually in response to the above error message can be automated by writing a VBA SubRoutine that can be run through the On Not In List Event Procedure. You don't need to close and reopen the Form to refresh the Combo Box contents either.

Add New Item through VBA.

  1. Open the Sales Form in Design View.

  2. Click on the Description Field to select the Combo Box control.

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

  4. Find and click on the On Not in List Property.

  5. Select Event Procedure from the drop-down list.

  6. Click the Build button (. . .) To open the VBA Module.

  7. Copy and paste the following Code into the Module, overwriting the top and bottom Procedure lines already appearing in the Module:

    Private Sub Description_NotInList(NewData As String, Response As Integer)
    Dim strmsg As String, rst As Recordset, db As Database
    
    If Response Then
        strmsg = "Entered Item not in List!" & vbCr & vbCr & "Add to List...?"
          If MsgBox(strmsg, vbYesNo + vbDefaultButton2 + vbQuestion, "Not in List") = vbYes Then
           Set db = CurrentDb
           Set rst = db.OpenRecordset("FruitList", dbOpenDynaset)
           rst.AddNew
           rst![Fruit] = NewData
           rst.Update
           rst.Close
           Me.Description.Undo
           Me.Description.Requery
           Me![Description] = NewData
           Me.Refresh
        End If
        Response = 0
    End If
    End Sub
  8. Save and Close the Sales Form.

    Trial Run Program.

  9. Open it in a normal view.

  10. Now, type the name of any fruit not available in the Combo Box list (say, Peach) in the Description field.

    You will be greeted with the following Message Box:

  11. Click the Command Button with the Label Yes to add the new item keyed in the Description Field to the Fruit List Table and refresh the Combo Box List.

  12. Now, click on the drop-down control of the Combo Box, and you can see that the new item is added to the list and accepted in the Description Field as well.

Share:

Input Masks and Data Entry

Input Masks and Data Entry.

Input masks are a special set of characters that can be applied to the Input Mask property of data fields in Microsoft Access to simplify data entry. They can also be used on Forms.

For example:

  • Text values can automatically convert to uppercase.

  • Slashes (/) can be inserted automatically in date formats to separate the day, month, and year.

  • Hyphens (-) can be inserted into telephone numbers to separate the country code, area code, and local number.

When entering large volumes of information manually, input masks greatly reduce effort, ensure consistency, and help maintain data in a standardized format for both entry and display.

Let us look at an example. Assume that we have a Text Field for entering Telephone Numbers, and the sample input mask Property setting is given below:

Input Mask of Telephone Number

(###) ###-#######;0;_

When the field is active before entering any values into the field, it will look like the display below:

(___) ___-____

The keystrokes you will make to type the telephone number are +914792416637, but the value will be automatically inserted in the appropriate segments, guided by the Input mask as (+91) 479-2416637. You don’t need to type the brackets, spaces, or hyphens that separate the country code, area code, and telephone number—these are inserted automatically by the input mask.

The Input Mask Property Value is expressed in three segments separated by semicolons.

The first segment value is the Input mask itself: (###) ###-#######.

The second segment value is 0 or 1. If the value is 1, the segment separator characters (brackets, spaces, and hyphens) are stored with the data in the field,  (+91) 479-2416637 (the field size must be large enough to store all the separator characters). If the value is 0, the keyed-in data alone is stored in the field as +914792416637, and the Input Mask is used for displaying the values.

The third segment value (the underscore character in the example) is used to indicate data entry positions with underscores.

When the Input mask character is # in all required character positions, it allows you to enter Digits, Spaces, plus, or Minus symbols only in the field, or leave the entire field empty.

The input mask character 9 works similarly, but it does not allow the use of plus (+) or minus (-) symbols in the data field.

The input mask character 0 restricts entry to digits 0–9 only, and, like 9, it does not permit plus or minus symbols.

Input Mask Date Field.

Input Mask Example2 (Date Field Input Mask): 99/99/0000;0;_

Sample Data Entry: _1/_1/1984 or 01/01/1984

Date value changes into 01/01/1984

In the Day and Month positions, you are allowed to enter a Space, but in the Year position, all four digits must be entered because the 0 input mask will not allow Spaces and cannot leave that area empty. But you can leave the Date Field totally empty.

Input Mask in Text Field.

Input Mask Example3 (Text Field): >CCCCCCCCCCCCCCC;0;_

Allows you to enter any Character or Space, or you can leave the data field blank. The Text Value entered will be converted to uppercase; you don't need to worry about the CAPS LOCK setting.

If you use the word Password as an Input Mask, then whatever data you enter into the field will appear as a series of * characters, and the actual value entered is not shown.

The list of Input Mask characters and their usage descriptions is given below.

Character    Description

0            Digit (0 to 9, entry required, plus [+] and minus [-] signs not allowed).

9            Digit or space (entry not required, plus and minus signs not allowed).

#            Digit or space (entry not required; spaces are displayed as blanks while in Edit mode, but blanks are removed when data is saved; plus and minus signs allowed).

L            Letter (A to Z, entry required).

?            Letter (A to Z, entry optional).

A            Letter or digit (entry required).

a            Letter or digit (entry optional).

&            Any character or a space (entry required).

C            Any character or a space (entry optional).

. , : ; - /  Decimal placeholder and thousand, date, and time separators (separator: A character that separates units of text or numbers.). (The actual character used depends on the settings in the Regional Settings Properties dialog box in Windows Control Panel).

<            Causes all characters to be converted to lowercase.

>            Causes all characters to be converted to uppercase.

!            Causes the input mask to display from right to left, rather than from left to right. Characters typed into the mask always fill it from left to right. You can include the exclamation point anywhere in the input mask.

\            Causes the character that follows to be displayed as the literal character (for example, \A is displayed as just A).

Password     Displays * in all keyed character positions.

You can use the above characters in mixed format to control or display field contents.

For example, the Input Mask>C<CCCCCCCCCCCCCC;0;_ will change the first character in uppercase and the rest of the text lowercase and accepts up to 15 characters in the field.

Technorati Tags:

Earlier Post Link References:

Share:

Menus with Option Group Control

Menus with Option Group Control.

We can create cascading menus on a form using Tab Controls and Option Group controls. Multiple menus can be arranged neatly, one behind the other, allowing the user to select the main menu option to display the corresponding submenu.

For example, the sample image below illustrates a Main Menu with three options, each representing a different category, along with submenu options for each category.

When the Data Files option is selected in the main menu, the corresponding Submenu appears on the right, allowing the user to click any option to open and work with that file.

Similarly, selecting Reports in the main menu displays the report options in the same area, replacing the previously shown data file options. Choosing the Views option brings up its respective sub-menu, again replacing the previous display.

In this way, multiple menus can be arranged and transitioned in the same space with a seamless, dynamic interface. These menus can be programmed using VBA or macros to run the detailed options associated with each selection.

Simple Interface Design and Code.

You don't need to work with any complicated VBA Programs except a few simple lines of Code and Macros. The design task is simple, and once you know the trick, you can implement it anywhere in no time.

The sample Design image of the above Form is given below:

  1. Open a new Form in the Design view.

  2. Select the Option Group Control from the Toolbox and draw it near the left side of the Form in the Detail Section.

  3. Enter the three Options (Data Files, Reports, and Views), pressing the Tab Key in each step to advance to the next line in the Wizard.

  4. Click Finish to create the Option Group Control with Radio Button Type Controls, with the Keyed-in Values as Labels.

  5. Change the Caption Value of the attached child label to Main Menu and position it above the Options Group control in the design.

  6. Click on the outer frame of the Options Group Control to select it and display its Property Sheet (View -> Properties).

  7. Change the Name Property Value to Frame0 and the Border color Property Value to 0.

  8. Select the Tab Control from the Toolbox and place it to the right of the Options Group Control (check the design image above).

    A Tab Control with two Pages will be created.  We must insert one more Page into the Tab Control.

  9. Right-click on the Tab Control to display the Shortcut Menu.

  10. Select Insert Page from the Shortcut Menu to add another Page to the Tab Control.

  11. While the Tab Control is in the selected state, display its Property Sheet.

  12. Change the Name Property Value to TabCtl9.

    NB: No dot (.) at the end of the name when you change it on the control.

    Data Tables Menu.

  13. Click on the First Page of the Tab Control to make it current.

  14. Select Option Group Control from the Toolbox and draw it on the First Page of the Tab Control.

  15. Enter the following Options (or Form Names of your own Tables in your Database) by pressing the Tab Key after each option on the Wizard:

    • Employees
    • Orders
    • Order Details
    • Customers
    • Products
  16. Click Finish to complete creation of the Option Group with Radio Button Style options.

  17. Display the Options Group Property Sheet (View ->Properties).

  18. Change the following Property Values as shown below:

    • Name = Frame1
    • Default Value = 0
    • Border Color = 0
  19. Change the Caption of the Child-Label attached to the Options Group Control to Data Files.  Change the Label width to the size of the Options Group Control. Position the Label above, as shown in the design image above.

    We must create two Option Group Controls on the 2nd and 3rd Pages of the Tab Control with a different set of Options.

    The Reports Menu.

  20. Follow Steps 13 to 19 to create an Option Group Control on the 2nd Page of the Tab Control with the following options, and name the Option Group Frame as Frame2 and the Child-Label Caption as Report List:

    • Employee Address Book
    • Employee Phone Book
    • Invoice
    • Monthly Report
    • Quarterly Report

    Create Report Names from your own Database, replacing the above List.

    Data View Menu.

  21. Create another Option Group Control on the 3rd Page of the Tab Control with the following options, or create your own Options and name the Option Group as Frame3 and Child-Label Caption as View Options:

    • View Inventory
    • View Orders
    • View Customers
    • View Suppliers

    Now, we have to write a few lines of VBA Code for the Main Menu Option Group to select the detailed Options Page of the Tab Control based on the menu selection. Even though Page Captions show something like Page10, Page11, and Page12, each Page is indexed as 0, 1, and 2. If you want to select the second Page of the Tab Control to display the Report Options, then you must address the Tab Control Page2 in Code as TabCtl9.Pages(1).Setfocus.

    We can select an individual Page of the Tab Control by clicking in the Page.  But this manual action will not synchronize with the Main Menu. The items on the Option Group Menu also have index numbers from 1 to the number of items on the Menu (Report List options 1 to 5).

    When the user selects an item on the Option Group Main Menu, we can test its index number in code and make its corresponding detailed menu on the Tab Control Page current.

    In the final refinement of the Menus, we will hide the Tab Pages of the Tab Control so that the Sub-Menus on them can be accessed only through the program, depending on the selection made on the Main Menu by the User.

    Code for Main Menu.

    First, the On Click Event Procedure of the Frame0 Option Group Control (Main Menu) allows the user to select the options and display their corresponding detailed Sub-Menu on the Tab Control. By default, the 1st item (Data Files) on the Main Menu is selected, and the Data Files list will be visible on the Sub-Menu.

  22. Display the Form Code Module (View -> Code) or click the Module Icon on the Toolbar Button.

  23. Copy and paste the following VBA Code into the Module:

    Private Sub Frame0_Click()
    Dim k
    k = Me![Frame0]
    Select Case k
        Case 1
            Me.TabCtl9.Pages(0).SetFocus
        Case 2
            Me.TabCtl9.Pages(1).SetFocus
        Case 3
            Me.TabCtl9.Pages(2).SetFocus
    End Select
    
    End Sub

    Trial Run of Menu.

  24. Save and close the Form named Main Switchboard.

  25. Open the Main Switchboard in a normal view.

  26. Click the 2nd option, Reports, in the Main Menu to display the Report List on the 2nd Page of the Tab Control.

  27. Try selecting other options on the Main Menu, and monitor the Submenu changes on the Tab Control Pages.

Forms Menu.

Now, we will write VBA Code similar to the above example to open Data File Forms when the User selects Options from the Sub-Menu.

  1. Open the Main Switchboard in Design View.

  2. Display the Code Module of the Form (View ->Code).

  3. Copy and paste the following VBA Code into an empty area of the Module:

    Private Sub Frame1_Click()
    Dim f1
    f1 = Me![Frame1]
    Select Case f1
        Case 1
            DoCmd.OpenForm "Employees", acNormal
        Case 2
            DoCmd.OpenForm "Orders", acNormal
        Case 3
            DoCmd.OpenForm "Order Details", acNormal
        Case 4
            DoCmd.OpenForm "Customers", acNormal
        Case 5
            DoCmd.OpenForm "Products", acNormal
    End Sub
  4. Save and Close the Main Switchboard Form.

    Macros for Report Menu.

    To run the Report Options, we will create a Macro and attach it to the Options Group Control (named Frame2) rather than using the VBA routine.

  5. Select the Macro tab in the Database window and select New to open a new Macro in the design view.

  6. You must display the Condition Column of the Macro by selecting the Toolbar Button with the Icon Image (or similar image) given below:

  7. Write the following Macro lines, as shown in the image given below, with the appropriate Parameter Values at the bottom Property Sheet for opening each Report in Print Preview/Print:

  8. Save the Macro named RptMac.

    Attach the Macro to Report Options.

  9. Open the Main Switchboard Form.

  10. Click on the 2nd Page of the Tab Control to display the Reports Option Group Menu.

  11. Click on the outer frame of the Options Group Menu to select it.

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

  13. Find and click on the On Click Property to select it.

  14. Click the drop-down list at the right edge of the Property, select the RptMac name in the On-Click Event Property.

     NB: You may create another Macro/VBA Routine for the third menu and attach it to the Frame3 Option Group Menu before doing the next step.

    In the next step, we will remove the pages of the Tab Control. Transitions between tab pages can be controlled entirely through code. This creates a seamless, “magical” effect for the sub-menu, allowing different menus to appear interchangeably in the same location.

    You can further refine the sub-menus by adjusting their dimensions and positions. Ensure you apply the same settings consistently to all three sub-menus on the Tab Control pages for a uniform appearance.

    • Top
    • Left
    • Width
    • height
  15. Click the outer edge of the Tab Control (or click on the right side of the third page) to select it.

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

  17. Find the Style Property in the Property Sheet and set it to None.

  18. Save and close the Main Switchboard Form.

  19. Open the Form in normal view and try out the Menu.

Share:

Digital Clock on Main Switchboard

Digital Clock on Main Switchboard.

You probably have several timekeeping devices around you—clocks, wristwatches, or even your computer—to check the current date and time. But why not add a digital clock to your project’s Main Switchboard form? This way, users can check the date and time at a glance, right in the middle of their work, without interrupting their workflow.

Beyond practicality, an animated digital clock also adds a touch of style to the Main Switchboard. All it takes is a label control on the Form and just a few lines of VBA code.

The clock automatically pauses whenever another form is opened over the Main Switchboard, and it restarts with the current time as soon as the Switchboard becomes active again.

If you’ve never used VBA in your databases and aren’t sure where to begin, this is the perfect opportunity to start with something simple, useful, and fun. Simple Clock Design.

Let us do it together.

  1. Open one of your existing Databases.

  2. If you have a Control Screen (Main Switchboard) in your database, then open it in Design View. You can open any Form in Design View to try this out.

  3. Display the Toolbox (View ->Toolbox) if it is not visible.

  4. Click the Label Tool to select.

  5. Draw a Label where you would like the Digital Clock to appear on the Form.

    For this example, I used a copy of the Main Switchboard form from the Microsoft Access sample database Northwind. The image below shows the form in Design View, with a Label control inserted for displaying the digital clock.

  6. Type at least one character (any character) in the Label control; otherwise, the Label control will disappear when you click elsewhere.

  7. While the Label Control is still in the selected state, display its Property Sheet (View ->Properties).

  8. Change the following Property Values as given below:

    • Name    =   lblClock
    • Width   =  1.5938"
    • Height   =  0.3125"
    • Border Style = Transparent
    • Font Size = 8
    • Font Weight = Bold
    • Text Align   =  Center

    Next, we need just two lines of VBA code to start the digital clock. The first line goes in the Form_Load() event procedure of the Switchboard form. This code starts the form’s IntervalTimer immediately after the Switchboard opens, ensuring the clock begins running as soon as the form is displayed.

  9. Click the form selector at the top-left corner of the form, where the horizontal and vertical rulers intersect, to select the entire form. The Property Sheet will now display the form-level properties. If the Property Sheet is closed, follow Step 7 above to reopen it and view the form’s properties.

  10. Find the On Load Property and click on it to select it.

  11. Select [EventProcedure] from the drop-down list box.

  12. Click on the Build (...) button at the right edge of the Property to open up the VBA Module with an empty skeleton of the VBA Sub-Routine as given below:

    The Form_Load() Event and Code.

    Private Sub Form_Load()
    
    End Sub
  13. Write (or copy) the following line of VBA Code in the middle of the above lines of Code:

    Me.TimerInterval = 1000 

    This line of code tells Access to pass program control to the form’s Timer subroutine (which we will write next) at one-second intervals. In other words, whatever code we place in the Timer subroutine will be executed once every second, sixty times per minute.

    In the Timer subroutine, we will add a single line of code to read the system date and time, and to update the label caption we created earlier. As a result, the label will display a continuously updating digital clock.

  14. Select Timer from the drop-down control at the top of the VBA Module Window.

    The opening and closing lines of the Timer Sub-Routine will be inserted into the VBA Module.  You must write the line given in the middle by inserting spaces and other punctuation correctly between double-quotes (date/time format string).

    Private Sub Form_Timer()
        Me.lblClock.Caption = Format(Now(), "dddd dd, mmm-yyyy hh:nn:ss")
    End Sub

    Alternatively, you can copy and paste all three lines of the VBA Code anywhere within the Form Module.

  15. Close and Save the Form.

  16. Open the Form in Normal View.

Your digital clock will show the Current Date and Time, and the time change is updated every second.

When other forms are open and overlapping the Switchboard or different programs and macros are running, the Main Switchboard Form becomes inactive. In such events, the digital clock can be temporarily turned off until the Switchboard becomes active again. This prevents unnecessary updates to the clock’s label and allows other programs to run more efficiently without interruptions from the clock’s timer.

We will write two more lines of code for the On Deactivate() and On Activate() Event Procedures to turn off the Timer (when the Main Switchboard is inactive) and to turn on (when the Main Switchboard is active again), respectively.

  1. Open the Form in Design View.

  2. Display the Form's VBA Module (View ->Code).

  3. Copy and paste the following VBA Code into an empty area of the Module.

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

    Trial Run of Form Activity.

  4. Save the Form and close it.

  5. Open it in the normal view.

  6. Open some other Form overlapping the Main Switchboard.

  7. Click on the Title Area of the second Form and drag it away from the Main Switchboard Form so that you can see the Digital Clock on it.

    You can see that the clock is not getting updated.

  8. Close the second Form.

Now the Main Switchboard Form becomes active, and the Clock will start updating the Date and Time again.

Technorati Tags:
Share:

Label Animation Zoom-out Fade

Label Animation Zoom-out Fade. 

Computer programming is fascinating because once you begin experimenting, it often sparks new ideas and leads you to try even more. I originally planned to demonstrate just one or two label animation techniques, but we’ve already explored five different animation methods.

Now, we’ll learn one more trick using the same form and labels we worked with last week. All you need to do is copy the new VBA code into the Form's code module.

The sample image below shows the program in action:

In this method, the color of each letter in the employee’s name gradually fades as if receding into the distance. At the same time, the size of each letter decreases progressively. The letters are displayed at fixed time intervals, creating an animated effect with the sense of three-dimensional depth.

Links to earlier Animation Styles.

If you have not tried out the earlier Label animation methods, you may explore them by visiting the following pages:

  1. Label Animation Style-1
  2. Label Animation Style-2
  3. Label Animation Variant
  4. Label Animation Zoom-in Style
  5. Label Animation in Colors

Let us try the new method.

The Design Task.

  1. Make a copy of the Employees form we used last week. On this form, create twenty small labels, and set their Name property to the values lbl01 through lbl20.

    A sample image of the Form is given below for reference:

  2. Open the Employees Form you have copied in Design View.

  3. Display the Form's Code Module (View -> Code).

  4. Copy and paste the following VBA Code into the Module, overwriting the existing Code:

    The Form Module Code.

    Option Compare Database
    Option Explicit
    
    Dim j, txtName, ctrl As Label, i
    
    
    Private Sub Form_Current()
    Dim t, xRGB As Long, fsize
    
    txtName = UCase(Me![first name] & " " & Me![Last name])
    fsize = 22
    For j = 1 To 20
       Set ctrl = Me("lbl" & Format(j, "00"))
       ctrl.FontSize = fsize
       ctrl.Caption = ""
       fsize = fsize - 1
    Next
       
    xRGB = RGB(10, 10, 10)
    i = xRGB
    For j = 1 To Len(txtName)
       Set ctrl = Me("lbl" & Format(j, "00"))
       xRGB = xRGB + i
       ctrl.ForeColor = xRGB
       ctrl.Caption = Mid(txtName, j, 1)
       
    t = Timer
    Do While Timer < t + 0.1
      DoEvents
    Loop
    
    Next
    
    End Sub
  5. Save the Form with the Code and open it in the normal view.

  6. Use the Record Navigation buttons to move forward or backward through the records, and observe how the employee name is displayed dynamically in the form’s header.

  1. Textbox and Label Inner Margins
  2. Animating Label on Search Success
  3. Label Animation Style-1
  4. Label Animation Style-2
  5. Label Animation Variant
  6. Label Animation Zoom-in Style
  7. Label Animation in Colors
  8. Label Animation Zoom-out Fade
Share:

Label Animation in Colors

Label Animation in Colors.

We have explored several label animation methods in the previous posts, and now we will try another trick using the last design you created: the Zoom-in method.

In this method, we add a splash of color—each letter of the employee’s name is assigned a randomly generated color. The letters are plotted in a “magical” sequence: odd-numbered letters appear first on odd-numbered labels (lbl01, lbl03, lbl05, etc.), followed by even-numbered letters on even-numbered labels (lbl02, lbl04, lbl06, etc.). The letters are displayed at fixed time intervals, creating a smooth animated effect.

After these two steps, the employee’s name is fully displayed in the form header, producing an eye-catching Zoom-in animation.

If you have tried the earlier label animation methods from last week, implementing this technique will be straightforward and easy to follow.

The Design Task.

  1. Make a Copy of the Employees Form we designed last week, and name it Employees_2 or any other name you prefer.

    The sample design of the Form, with twenty labels placed close together in the Header of the Form, with the Name Property Values set as lbl01 to lbl20, is given below:

  2. Display the Form's Code Module (View -> Code) after opening the Form in Design View.

  3. Copy and paste the following VBA Code into the Form Module, overwriting the existing Code.

    The Form Module Code.

    Option Compare Database
    Option Explicit
    
    Dim j, txtName, ctrl As Label
    
    Private Sub Form_Current()
    Dim t, m, R, G, B
    Randomize (Timer)
    
    txtName = Me![first name] & " " & Me![Last name]
    For j = 1 To 20
       Set ctrl = Me("lbl" & Format(j, "00"))
       ctrl.Caption = ""
    Next
    For j = 1 To Len(txtName) Step 2
       Set ctrl = Me("lbl" & Format(j, "00"))
       R = Int(Rnd(1) * 64)
       G = Int(Rnd(1) * 128)
       B = Int(Rnd(1) * 255)
    
       ctrl.ForeColor = RGB(R, G, B)
       ctrl.Caption = Mid(txtName, j, 1)
    
    t = Timer
    Do While Timer < t + 0.1
      DoEvents
    Loop
    Next
    
    For j = 2 To Len(txtName) Step 2
       Set ctrl = Me("lbl" & Format(j, "00"))
       R = Int(Rnd(1) * 255)
       G = Int(Rnd(1) * 128)
       B = Int(Rnd(1) * 64)
    
       ctrl.ForeColor = RGB(R, G, B)
    
       ctrl.Caption = Mid(txtName, j, 1)
    
    t = Timer
    Do While Timer < t + 0.1
      DoEvents
    Loop
    
    Next
    
    End Sub
  4. Save the Form with the new VBA Code.

    The Demo Run.

  5. Open the Form in the normal view.

  6. Use the record navigation button to move the record forward or back and watch how the employee name is displayed in the header labels.

The sample screen in Normal View is given below:

    Each name character is displayed in a different color at a 0.1-second interval, creating a smooth animated effect. The color codes are generated randomly.

    In this program, we use two delay loops instead of the form’s default Timer Interval event procedure.

    You can adjust the animation speed by modifying the value in the line:

    Do While Timer < t + 0.1

    For example:

    • 0.5 will slow down the animation.

    • 0.05 will make it run faster.

    This gives you full control over the speed of the Zoom-in effect.

  1. Textbox and Label Inner Margins
  2. Animating Label on Search Success
  3. Label Animation Style-1
  4. Label Animation Style-2
  5. Label Animation Variant
  6. Label Animation Zoom-in Style
  7. Label Animation in Colors
  8. Label Animation Zoom-out Fade
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