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

Custom Calculator and Eval Function

Custom Calculator and Eval Function.

When we think of a calculator, the image that usually comes to mind is the traditional type with buttons labeled 0–9 and the standard arithmetic operators. Windows already includes such a calculator under Accessories, which can even be switched to Scientific mode — so there’s no need to recreate that in MS Access.

Instead, we’re going to design a different kind of calculator — one that can evaluate defined expressions consisting of data field names, constants, arithmetic operators, and parentheses (to control the order of operations). This calculator will allow you to input an expression, have Access evaluate it, and display the result instantly.

There’s no need for a complex interface. All we require is:

  • A TextBox to enter the expression,

  • A Command Button to trigger the evaluation, and

  • A few lines of VBA code to process the calculation.

The result can be displayed either in a MsgBox or in another TextBox on the form.

Before we begin building the calculator, let’s look at one of Access’s most powerful yet underused built-in functions — the EVAL() function. This function will serve as the core engine of our custom calculator. With EVAL(), you don’t need to worry about following mathematical rules manually — such as evaluating parentheses first, then exponentiation, followed by multiplication and division (from left to right), and finally addition and subtraction. Simply pass the expression as a string to the EVAL() function, and it will return the correctly computed result.

EVAL() Function Usage.

Try a few examples quickly to get a feel for it. Open the VBA Module Window (Alt+F11) and open the Debug Window (Ctrl+G). Type the following expressions in the Debug Window and press the Enter Key:

? EVAL("2+3*4/2")

Result: 8

? EVAL("(2+3)*4/2")

Result: 10

? EVAL("log(SQR(625))/log(10)")

Result: 1.39794000867204

? Eval("10^" & "Eval('log(Sqr(625))/log(10)')")

Result: 25

? EVAL("Datediff('yyyy',Forms!Employees!BirthDate,date())")

Result: 45 (the Employees Form must be open)

EVAL() the Expression Parser

From the above examples, we can see that you can write expressions in a TextBox using built-in functions, data field references, and numeric constants. The Eval() function then parses the expression and returns the result. This gives the user the flexibility to define and evaluate custom expressions dynamically, incorporating live data from form fields into their calculations.

Tip: The Eval() function can do much more than just evaluate formulas. It can also run other functions, trigger the Click event of a command button, or execute a macro programmatically. For additional details and examples of how Eval() can be used, open the Microsoft Access Help window in the VBA editor and search for “Eval Function.”

The sample Demo Project.

I have created a sample database (available for download at the bottom of this post) designed for an auto dealership that offers credit facilities to customers at nominal interest rates of 6%, 7%, or 8%, repayable in 24, 36, or 60 installments, respectively. The salesperson is responsible for determining the most suitable repayment plan for each customer, including the percentage of down payment, installment schedule, and applicable interest rate.

To encourage sales, the salesperson is also authorized to offer customers a discount of up to 20% on the Maximum Retail Price (MRP), based on negotiation and customer eligibility.

An image of the Form he uses to run these calculations is given below:

This is a stand-alone form (which can optionally be linked to a table) containing unbound text boxes. Each text box is labeled with its corresponding name displayed to the left. When writing expressions, it is essential to properly qualify the control names, for example:
Forms!CustomCalculator!Balance

Note that shorthand references such as Me!Balance are not accepted in this context. This can make it somewhat cumbersome to build expressions, especially when multiple field names are involved in a formula.

The VBA Code.

We have created a small VBA routine that recognizes text box names enclosed in square brackets [ ], retrieves their corresponding values, and substitutes them into the expression before passing it to the Eval() function.

For easier expression entry, a combo box containing arithmetic operators and text box names (in square brackets) is provided on the form. The colored display control below shows, for informational purposes, the expression after the text box references have been replaced with their actual values. Just before it is submitted to the Eval() function.

When the Calculate Command Button is clicked, the result of the calculation is displayed in the Text Box with a dark background and the label Result. The VBA Code is given below:

Private Sub cmdCalc_Click()
'-----------------------------------------------------------
'Author : a.p.r. pillai
'Date    : November, 2008
'URL     : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------------
Dim str As String, loc1 As Integer, chk As Integer
Dim strout As String, loc2 As Integer, loc3 As Integer
Dim strin As String
Const sqrleft As String = "["
Const sqrright As String = "] "

On Error GoTo cmdCalc_Click_Err

'change the reference if different
str = Me![Expression]

loc1 = InStr(1, str, sqrleft)
If loc1 > 0 Then
   strin = Left(str, loc1 - 1)
   strout = Left(str, loc1 - 1)
   loc2 = InStr(loc1, str, sqrright)
End If
Do While loc2 > 0
   strin = strin & Mid(str, loc1, (loc2 - loc1) + 1)
   strout = strout & Me(Mid(str, loc1, (loc2 - loc1) + 1))
   loc1 = InStr(loc2 + 1, str, sqrleft)
   If loc1 > 0 Then
     loc2 = InStr(loc1, str, sqrright)
      If loc2 = 0 Then
         MsgBox "Errors in Expression, correct and retry. "
         Exit Sub
      Else
         strout = strout & Mid(str, Len(strin) + 1, loc1 - (Len(strin) + 1))
         strin = strin & Mid(str, Len(strin) + 1, loc1 - (Len(strin) + 1))
      End If
   Else
     loc3 = loc2
     loc2 = 0
   End If
Loop

If Len(str) > loc3 Then
   strout = strout & Mid(str, loc3 + 1)
End If

'this line can be removed if not required
Me![parsed] = strout

'change the reference, if different
Me![result] = Eval(strout)

cmdCalc_Click_Exit:
Exit Sub

cmdCalc_Click_Err:
MsgBox Err.Description, , "cmdCalc_Click()"
Resume cmdCalc_Click_Exit
End Sub

Private Sub cmdReset_Click()
Me![Expression] = Null
Me![parsed] = Null
End Sub

Note: There is no validation check included in the Code to detect misspelled names or unbalanced parentheses, etc. These shortcomings will automatically generate an error when the EVAL() function executes. The user will be able to review the expression, make corrections, and retry.

Download.

You can implement this program on any Form with a small change in str = Me![Expression] and Me![result] = Eval(strout) lines in the Code, if different names are used. Customize the Combo Box contents based on your input Field Names.


Share:

Data Editing And Security Issues

Data Editing And Security Issues.

Data entry and editing are among the most crucial activities for keeping a database accurate and up to date. These steps ensure that the information remains reliable and ready for generating meaningful reports and analysis. To make data entry easier and more efficient for users, it is good practice to include combo boxes, check boxes, and calculated fields—for example, automatically determining a Payment Due Date as 30 days after the Material Delivery Date.

Another key consideration is data security. Here, the focus is not on preventing unauthorized external access—MS Access already provides robust built-in security features for that—but rather on protecting the data from accidental modifications or deletions by authorized users during routine operations.

For example, suppose our Employee database includes a Memo field that stores detailed information about each employee’s educational background and prior work experience. Normally, when the cursor (insertion point) moves into a field, the entire content of that field becomes highlighted and selected. At this stage, if the user’s attention is momentarily diverted and a key is pressed accidentally, the entire content of the field may be deleted. If the user does not immediately notice this or forgets to restore the data using Ctrl + Z (Edit → Undo Typing), the information could be lost permanently.

Protecting from unintended Changes.

We will focus on this specific cursor behavior and explore how to provide protection against inadvertent data loss. The way the cursor behaves when entering a field is determined by the settings found under the Keyboard tab of the Options dialog box (available from the Tools menu). Under the Behavior Entering Field section, you will find three different options, as shown in the image below:

The first option, Select Entire Field, is the default setting. However, choosing one of the other two options is generally advisable to prevent the kind of data loss we are focusing on. Of the remaining two, my preferred choice is Go to End of Field. The reason is simple—when this option is selected, even if you accidentally press the Delete key or any other key, the insertion point is positioned at the end of the field content, and the existing information remains safe.

Since this is a global setting in Microsoft Access, any manual changes you make here will affect all forms in every database opened on your machine. Conversely, a database you design on your system will not carry these settings when opened on another computer in a multi-user environment. Moreover, you may not want this behavior applied to every form in your database.

The best approach, therefore, is to enable this feature programmatically through a VBA routine and restore the default settings when leaving that particular form. In a shared network environment, users may have different default settings for the “Behavior Entering Field” option on their own machines, so it’s important not to change these preferences permanently.

The following is the list of numeric values of each 'Behavior Entering Field' Option setting:

Behavior | Description | Option Values.
  1. Select Entire Field - 0
  2. Go to Start of Field - 1
  3. Go to End of Field - 2

When opening a form that requires this modified cursor behavior, we will follow specific steps to enable it upon form initialization. Then, when the form is closed, we will restore the default settings to ensure that the global behavior of Access remains unchanged.

  1. Save the current default setting of Behavior Entering Field before it is changed.

  2. Change the setting to Go to the end of Field behavior for the current session of the Form.

  3. Reset it back to the saved value in Step 1 above, before closing the Form.

We can achieve this with the following Event Procedures in the Form Module:

Option Compare Database
Dim DefaultBehavior As Integer

Private Sub Form_Load()
    DefaultBehavior = Application.GetOption("Behavior Entering Field")
    Application.SetOption "Behavior Entering Field", 2
End Sub

Private Sub Form_Unload(Cancel As Integer)
    Application.SetOption "Behavior Entering Field", DefaultBehavior
End Sub

Copy and paste the above Code into the Form's Code Module and save the Form. The Dim DefaultBehavior As Integer statement must be placed in the Global area of the Module as shown above.

Try out the New Setting.

Open the Form in normal View and try moving the cursor from one field to the other by tapping the Tab Key or the Enter Key. The insertion point will position at the end of the field contents.

Share:

Event Trapping Summary On Datasheet

Event Trapping Summary On Datasheet.

How do we execute the Event LostFocus() and GotFocus() procedures in the Datasheet view?

How to display the Summation of numeric values in the Datasheet view?

For answers to both questions, we need a sample Table and a Datasheet Form.

Import the following tables from the Northwind.mdb sample database C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb.

  • Order_Details
  • Products

The Products table is also required because the ProductID field in the 'Order_Detail' table references it through a Combo Box. Without the Products table, the Combo Box would have no source from which to retrieve Product IDs, leaving the ProductID field in the Order_Detail table unpopulated and preventing the relationship from functioning correctly.

Design a Datasheet Form

  1. To create a Datasheet Form, click on the Order_Detail Table, select Form from the Insert Menu, and select Autoform: Datasheet from the displayed list of options in the Formwizard.

    A Datasheet form will be created and will open the Table contents in Datasheet View.

  2. Select the Save As... option from the File Menu and give the name Order Details for the Form. The Datasheet Form will be saved, but it is not closed.

  3. Select Design View from the View Menu to change the Form to Design View mode.

The Form in Design View should look like the image shown below, although the appearance may vary slightly depending on your version of Microsoft Access.

Doesn't matter how the Fields are arranged on the Form, whether in Row or Column Format, the data will always be displayed in Datasheet format. The placement of Fields will not affect the way the data is displayed on the Datasheet, but the Tab Order does.

The Tab Order of Controls

Let us find out how the Field's Tab Order influences the Datasheet View.

  1. Change the Form into Datasheet View (View -> Datasheet View) and check the order of fields appearing in there.

  2. Change the View into Design mode again and rearrange the ProductID and UnitPrice fields by switching their places.

  3. Change the View back to Datasheet and inspect the data field order.

    There will not be any change in the Order of Fields displayed from the previous View. If you move the Cursor using the Tab Key, then it moves in the same order as the fields' placement, as you have seen earlier before switching the fields.

  4. Change the Form back to Design View again.

  5. Select Tab Order... from the View menu. Click on the left border of the UnitPrice field on the Tab Order Control, click and drag it up, and place it below the OrderID field.

    Tip: You can click on the Auto Order Command Button to re-arrange the Tab Order according to the field placements on the Form.

  6. Open the Form in normal view now and check the change of field placements.

The Unbound Text Box.

We will add one Unbound Text Box on the Form to calculate the Extended Price after adjusting the discounts of each item.

  1. Open the form in design view if you have closed it.

  2. Drag the Form Footer Section down to get more room to place another Text Box below, or you can place it to the right of the Discount Field, too.

  3. Create a Text Box and write the formula =(1-[Discount])*[UnitPrice]*[Quantity] in it.

  4. While the Text Box is still in the selected state, display the Property Sheet (View -> Properties).

  5. Change the Format Property value to Currency format. Change the Name Property value to Extended Price.

  6. Open the Form in normal view and check the newly added Text control heading at the top. It will be something like Text10:.

    In Datasheet View of Forms, MS Access uses the Caption of the Child Labels attached to the text boxes as Field headings. We have changed the Name Property of the Text Box to Extended Price, but that is ignored here.

  7. Now, change the Form into Design view and delete the Child Label attached to the Extended Price Text Box.

  8. Change to Datasheet view again and check the field name appearing at the top; it will be Extended Price now.

Datasheet Event Procedure.

  1. To try an Event Procedure on the Datasheet view, copy and paste the following VBA Code into the Form's Code Module (View -> Code to display the Code Module of the Form) and save the Form with the Code.

    Private Sub UnitPrice_LostFocus()
    Dim newUnitPrice As Double, msg As String
    Dim button As Integer
    
    button = vbQuestion + vbYesNo + vbDefaultButton2
    
    If Me![UnitPrice] = Me![UnitPrice].OldValue Then
       msg = "Replace UnitPrice: " & Me![UnitPrice].OldValue & vbCr & vbCr
       msg = msg & "with New Value: " & Me![UnitPrice]
    
       If MsgBox(msg, button, "UnitPrice_LostFocus()") = vbNo Then
            Me![UnitPrice] = Me![UnitPrice].OldValue
        End If
    End If
    
    End Sub
    

    The change in the UnitPrice field is trapped, and the User is alerted about the attempt and asked to reconfirm the change or cancel it.

  2. Open the Form in the datasheet view and make some changes in the UnitPrice Field and leave the Field by pressing the Tab Key or Enter key.

A Message Box will appear asking for permission to retain the change or to cancel it.

Datasheets can be programmed with Event Procedures (either Field-level or Form-level) for validation checks and information display.

Displaying of Summary Information.

Method-1

We will attempt to answer the second question we have raised on top of this page.

  1. Open the Order_Details Form in Design View.

  2. Drag the Form Footer Section down to get enough room to place two TextBoxes. Create two TextBoxes in the Form Footer Section.

  3. Write the formula =Sum([Quantity]) in the first Text Box.

  4. Display the Property Sheet of the Text Box and change the Name Property value to TOTALQTY.

  5. Write the formula =Sum((1-[Discount])*[UnitPrice]*[Quantity]) in the second Text Box.

  6. Change the Name Property Value to TOTALVALUE.

When we open the Order_Details Form in Datasheet View, it will calculate the Summary Values in TOTALQTY and TOTALVALUE TextBoxes on the Footer of the Form, but we must do something to display them.

The first idea that usually comes to mind is to use a MsgBox to display the results within a Form’s event procedure. However, since the underlying records may change over time, these updates should be reflected in the summary values. Therefore, we must ensure that the results are refreshed to display the latest data before displaying them again.

We will implement this method before we settle on a better one.

  1. Copy and paste the following Code into the Form's Code Module and save the Form:

    Private Sub Form_DblClick(Cancel As Integer)    
    Dim msg As String
         Me.Refresh
        msg = "Total Quantity = " & Me![TOTALQTY] & vbCr & vbCr
        msg = msg & " | Total Value = " & Format(Me![TOTALVALUE], "Currency")
    
         MsgBox msg
    End Sub
    
  2. Open the Form in Datasheet View.

  3. Double-click on the Record Selector at the left border of the Form.

    A Message Box pops up with the Summary Values from the TextBoxes in the Form Footer Section.

  4. Make some changes to the Quantity and UnitPrice fields to try Step 3 again. The value changes will appear in the Message Box.

  5. You can filter the Data on ProductID or on OrderID by right-clicking on these fields and selecting Filter by Selection or other Options available on the displayed Shortcut Menu, and by executing Step 3 to get the Summary of selected records.

Method-2

After trying out the above method, your response may be something like "Yeah.. it serves the purpose, but it doesn't give the impression of a sophisticated method. After all, it takes so many clicks and pop-up Message Boxes". I agree with you, too.

With a small change to the above Code, we can make the results the way you like them.

  1. Open the Form in Design View.

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

  3. Select the Mouse Move Property and select Event Procedure from the drop-down control.

  4. Click on the build (...) button on the right side of the Property to open the Form's Code Module.

  5. Cut the Code lines from within the Form_DblClick() Event Procedure:

    Private Sub Form_DblClick(Cancel As Integer)
    
    End Sub
    

    Leave the above lines alone and paste the Code into the Form_MouseMove() Event Procedure.

  6. Change the line that reads:

    MsgBox msg

    to

    Me.Caption = msg

    After the change, the Code will look like the following:

    Private Sub Form_DblClick(Cancel As Integer)
    
    End Sub
    
    Private Sub Form_MouseMove(button As Integer, Shift As Integer, X As Single, Y As Single)
    Dim msg As String
        Me.Refresh
        msg = "Total Quantity = " & Me![TOTALQTY] & vbCr & vbCr
        msg = msg & " | Total Value = " & Format(Me![TOTALVALUE], "Currency")
        Me.Caption = msg
    End Sub
    
  7. Open the Form in Datasheet View and move the Mouse over into the data area by crossing the Field Headings or the Record Selectors on the left side.

  8. Check the Title Area of the Datasheet View, and you will find the Summary information is displayed there. A sample image is given below:

Now try changing the field values or filtering the data and moving the Mouse over the Field Headings or Record Selectors to get the result on the Title Bar instantly. No Message Boxes or Double-Clicks, and what do you say about that?

Share:

Sum Min Max Avg ParamArray

Sum Min Max Avg ParamArray.

I’m sure your first reaction after reading the title might be, “I already know all that—tell me something new!” If you haven’t come across the last item in the title (the odd one out), then that’s exactly what I plan to share here—so keep reading.

The first four terms are quite familiar; they refer to built-in functions in Microsoft Access and worksheet functions in Excel. We’ll get to the last one a little later, but first, let’s look at how the Min() function works in Excel—and why using it in Microsoft Access presents a few challenges in comparison.

Difference between Excel and Access.

We’re certainly not forgetting the other domain aggregate functions in Access—DCount(), DSum(), DMin(), DMax(), and DAvg().

Let’s start by looking at how the Min() worksheet function works in Excel. It can identify the minimum value from a range of cells in a single column, a row of cells across multiple columns, or even a block of cells spanning several rows and columns.

However, when we return to Microsoft Access, the Min() function behaves differently. It can only be applied to a single column (that is, a single field) within a query, or in the header and footer sections of forms or reports. So, how do we determine the minimum value across multiple fields?

Go through the sample table below to better understand the issue we’re dealing with.

We have received Quotations for Electronic Items from three different Suppliers, and we need to know which quotation is the lowest and from which Supplier. In this case, our Min() Function has no use here unless we reorganize the above data in the following format:

To obtain the desired result from this data, we’ll need to create two queries, setting aside—for now—issues such as duplicate descriptions, supplier names, or the overall table size.

  1. First Query (Total Query):
    Group the data by the Desc field and use the Min() function to determine the lowest value from the Values field.

  2. Second Query:
    Use both the original table and the first query as data sources. Join them on the Desc and MinOfValues fields from the Total Query with the Desc and Values fields of the base table. This will return all records from the table that match both the description and the lowest quoted value.

The ParamArray Method.

I consider these steps to be excessive work, and I know you will agree too. Instead, we can write a User Defined Function with the use of ParamArray and pass the Field Names to the Function and find the Minimum Value from the list. Here is a simple Function with the use of the ParamArray declaration to find the Minimum Value from a List of Values passed to it.

Public Function myMin(ParamArray InputArray() As Variant) As Double
'------------------------------------------------------------------
'Author : a.p.r. pillai
'Date   : November-2008
'URL    : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------------------
Dim arrayLength As Integer, rtn As Double, j As Integer

'calculate number of elements in Array
arrayLength = UBound(InputArray())

'initialize Null values to 0
For j = 0 To arrayLength
   InputArray(j) = Nz(InputArray(j), 0)
Next
'initialize variable with 1st element value
'or if it is zero then a value with high magnitude
rtn = IIf(InputArray(0) = 0, 9999999999#, InputArray(0))

For j = 0 To arrayLength
    If InputArray(j) = 0 Then
 GoTo nextitem
   If InputArray(j) < rtn Then
        rtn = InputArray(j)
    End If
nextitem:
Next

myMin = rtn
End Function

Copy and paste the above Code into a Global Module and save it.

A few simple rules must be kept in mind while writing User Defined Functions using the ParamArray declaration in the Parameter list of the Function.

  1. While declaring the Function, the Parameter Variable InputArray() (or any other name you prefer) must be declared with the keyword ParamArray, in place of ByRef or ByVal we normally use to declare parameters to functions.

  2. The Data Type must be a Variant type.

  3. The ParamArray declaration must be the last item in the Parameter list if the UDF accepts more than one Parameter.

  4. The Optional parameter declarations should not appear before the ParamArray declaration.

  5. Since the data type is Variant, it can accept any value type.

Using the above myMin() Function, we have created a Query on the first Table given above. The SQL and the resulting image of the Query in Datasheet View are shown below.

SELECT MaterialQuote.Desc,
 MaterialQuote.Supplier1,
 MaterialQuote.Supplier2,
 MaterialQuote.Supplier3,
 mymin([supplier1],
[supplier2],
[supplier3]) AS Minimum,
 IIf([minimum]=[supplier1],"Supplier1",IIf([minimum]=[supplier2],"Supplier2",IIf([minimum]=[supplier3],"Supplier3",""))) AS Quote
FROM MaterialQuote;

In the above example, we have used only three Field Values to pass to the Function, and these can vary depending on your requirement.

Modified Version of VBA Code

A modified version of the same function is given below that accepts a Calculation Type value (range 0 to 3) as the first Parameter, and depending on that, we can find the Summary, Minimum, Maximum, or Average values passed to it through the InputArray() Variable.

Option Compare Database

Enum SMMA
    accSummary = 0
    accMinimum = 1
    accMaximum = 2
    accAverage = 3
End Enum

Public Function SMMAvg(ByVal calcType As Integer, ParamArray InputArray() As Variant) As Double
'------------------------------------------------------------------------
'calType : 0 = Summary'        : 1 = Minimum
'        : 2 = Maximum'        : 3 = Average
'------------------------------------------------------------------------
'Author  : a.p.r. pillai'Date    : November 2008
'URL     : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------------------------
Dim rtn As Double, j As Integer, arrayLength As Integer
Dim NewValue As Variant

On Error GoTo SMMAvg_Err

If calcType < 0 Or calcType > 3 Then
     MsgBox "Valid calcType Values 0 - 3 only", , "SMMAvg()"
     Exit Function
End If

arrayLength = UBound(InputArray())
'Init Nulls, if any,  to 0
For j = 0 To arrayLength
   InputArray(j) = Nz(InputArray(j), 0)
Next

For j = 0 To arrayLength
    NewValue = InputArray(j)
    'skip 0 value
    If NewValue = 0 Then
 GoTo nextitem
    End If
    Select Case calcType
    'Add up values for summary/average
        Case accSummary, accAverage
            rtn = rtn + NewValue
        Case accMinimum
            rtn = IIf(NewValue < rtn, NewValue, rtn)
            rtn = IIf(rtn = 0, 9999999999#, rtn)
        Case accMaximum
            rtn = IIf(NewValue > rtn, NewValue, rtn)
    End Select
nextitem:
Next

'Calc Average
If calcType = accAverage Then
   rtn = rtn / (arrayLength + 1)
End If

SMMAvg = rtn

SMMAvg_Exit:
Exit Function

SMMAvg_Err:
MsgBox Err.Description, , "SMMAVG()"
SMMAvg = 0
Resume SMMAvg_Exit
End Function

The Function name was defined using the first letters of the Calculation Types that the Function can perform, and I hope you like it too.

When any of the values in the InputArray() element is zero, that is ignored and will not be taken as the minimum value.

Sample Runs on Immediate Window:

? SMMAvg (0,0,10,5,7) 'Summary
 Result: 22 

? SMMAvg (1,0,10,5,7) 'Minimum value from 0,10,5,7
 Result: 5
 
? SMMAvg (2,0,10,5,7) 'Maximum value from 0,10,5,7
 Result: 10 
 
? SMMAvg (3,0,10,5,7) 'Average
 Result: 5.5 
  

We can use this Function in Text Boxes on Forms,  Reports, or from other Controls. Use it at your own risk.

Share:

Textbox And Label Inner Margins

Textbox And Label Inner Margins.

Whether it’s a Form or a Report, a well-crafted design always draws the attention of both the user and any onlooker. Everyone designs forms and reports—but if you give the same task to five different people, each will produce a unique result based on their individual skills and sense of artistry unless they all rely on the same built-in wizards.

Most users focus primarily on the information presented in a report and want it organized and accurate. However, how that information is presented is entirely up to you—and it often depends on how much time you can invest in the design process. Remember, you typically design a report only once as part of a project, so it’s worth doing it thoughtfully.

Your report may eventually circulate far and wide, through faxes, emails, or shared databases, to reach a much wider audience. When compared with other reports circulating around, you’d want someone to pause and ask, “Who designed this one?” Fortunately, Microsoft Access provides all the tools you need to create visually appealing, professional-quality reports and forms. With just a bit more time and creativity, you can achieve remarkable results using the simple yet powerful tools Access offers.

Precision Positioning of Data.

Here, I’d like to introduce you to a few important properties of TextBoxes and Labels on a report—and show you how a few simple design adjustments can transform an ordinary layout into a professional, visually appealing report.

The image below shows a Tabular Report created using the Report Wizard in Microsoft Access.

Wizards are excellent tools for quickly laying out all the objects on Forms or Reports with default formatting for font type, size, and style—saving a significant amount of design time. All that’s left is to fine-tune the layout to suit your preferences.

A Sample Project.

If you’d like to try this simple design step by step, import the Shippers table from the sample database at
C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb. (That path is for Access 2003 — if you’re using a different version, look for the appropriate \Office##\ folder.) After importing, select the Shippers table, choose Report from the Insert menu, and pick Auto Report: Tabular from the options. Access will generate the report in moments. A preview of the report in Print Preview is shown below:

The modified version of the same Report in Print Preview below:

The transformation was easy with only a few changes to the above design, and I know which change you have noticed first. If I have turned on the borders of the TextBoxes and Labels alone, then the Print Preview will look like the one below:

Make the following changes to the above design:

  1. Delete the thick line under the Header Labels.

  2. Point the Mouse on the vertical ruler to the left of the Header Label Shippers so that it turns into an arrow pointing to the right, and then click and drag along the ruler downwards so that you can select all the Labels and Text Boxes in the Report Header, Page Header, and Detail Sections together.

    Alternatively, you can click on an empty area of the Report and drag the Mouse over all the controls to select them. Do not select the Page Footer Section Controls. We don't need them in this Report.

  3. Display the Property Sheet (View -> Properties) and change the following Values:

    • Border Color = 9868950
    • Special Effect = Flat
    • Border Style = Solid
    • Border Width = Hairline

    You need to change only the Border Color Value; others will be there as default. If not, then change them as given above.

  4. Select all the Field Header Labels alone in the Page Header Section, as we did in Step 2 above. Select Format -> Align -> Left to arrange the labels close together horizontally without leaving gaps between them.

  5. Display the Property Sheet of the selected Labels (View -> Properties) and change the Top Property Value to 0 and Height Property Value to 0.4167 Inches.

    Centralizing Text Vertically.

  6. Centralize the Text horizontally within the Labels by changing the Text Align Property Value to Center, while all the Labels are still in the selected state.

  7. Select all the TextBoxes in the Detail Section together and select Format -> Align -> Left to arrange the TextBoxes close together without leaving gaps between them.

  8. Display the Property Sheet of the TextBoxes (if you have already closed it) and change the Top Property Value to 0 and the Height Property Value to .2917" so that the data lines are not too close and crowded when Previewed/Printed.

  9. If there is a gap below the Labels in the Page Header Section and below the TextBoxes in the Detail Section, then close them by dragging up the Detail Section Header and the Page Footer Bars.

  10. Delete all the Page Footer Section controls. Close the gap by dragging the Report Footer Bar up.

  11. Next, resize the Report Header label containing the Shippers heading so that it spans the combined width of all the field header labels in the Page Header section. You can do this either by adjusting it manually by eye or by opening the Property Sheet for each header label, noting their individual Width property values, adding them together, and then setting the Width property of the Shippers heading label to that total.

  12. Change the Height Property Value to 0.416, and the Text Align Property Value to Center.

  13. Save your Report with a Name of your choice.

    With the above modifications, the Report Print Preview image is shown below and needs to be corrected.

The Report looks good, but with a few more cosmetic changes, it will look even better.

  1. The Field Header Labels' Caption Text must be vertically centered.

  2. The Shipper ID Numbers and other field values are too close to the Border Line, and they should be positioned a little away from the border.

  3. Open the Report in Design View and select all the Field Header Labels together as we did earlier.

  4. Display the Property Sheet and drag the right scroll bar of the Property Sheet down to the bottom. There, you will find the Inner Margin Properties that you can use to position the Text within the Controls.

    NB: These Properties are available only in MS Access 2000 and later versions.

  5. Change the Top Margin Property Value of Header Labels to 0.1".

  6. Select the Text Controls together on the Detail Section and change the Top Margin Property Value to 0.0701".

  7. Select the Shipper ID TextBox in the Detail Section, and change the Right Margin value to 0.1".

  8. Select the Company Name TextBox, and change the Left Margin Value to 0.0597" and set the same value for Phone Number also.

  9. Save your Report and open it in Print Preview. It is similar to the 3rd Image from the top of this page.

Although the explanation may seem lengthy, once you understand the steps, you can complete the design in just a few minutes.

Share:

Multiple Parameters For Query

Multiple Parameters For Query.

Queries are an essential component of data processing, and we rely on them extensively in various ways. One of the main challenges when creating queries is how to filter data in a user-friendly manner, making the process seamless for the user. To address this, we employ several methods that allow users to easily pass values as criteria to the queries.

  1. You can create Parameter Queries by inserting variables, such as:[EnterSalesDate]', Into the Criteria row of a query. When run, the query will prompt the user to enter the parameter value, allowing them to filter records directly. To define the data type for a parameter variable, use the Parameters… option from the Query menu while in Design View.

  2. You can place TextBoxes or Combo Boxes on a Form, where the user can enter or select values before running a Report or viewing data. The underlying queries reference these controls in their Criteria rows—for example, Forms![MyForm]![myDateCombo]. Based on the values entered or selected, the queries filter the data accordingly, producing the desired results in Reports or data views.

  3. Another way to filter records is by specifying a range of values. For example, to retrieve Sales records for a particular period, the query criteria for the Sales Date might be : Between #01/01/2008# AND #03/31/2008# if constants are used. Alternatively, these values can be dynamically passed from TextBoxes on a Form, allowing the user to specify the date range interactively.

    In such cases, I prefer to create a small table—let’s call it a Parameter Table—with a single record and two fields: StartDate and EndDate. Then, I create a Datasheet Form for this table and embed it as a Sub-Form on the Main Form. This allows the user to conveniently enter the date range values directly into the table.

    This table is included in the main query, with the StartDate and EndDate fields placed in the Criteria row using the expression:

    Between [StartDate] AND [EndDate]

    It is important to note that the Parameter Table should contain only one record; otherwise, the main table’s results will be duplicated if the Parameter Table has multiple records. To prevent this, set the Allow Additions property of the Datasheet Form to No, so the user cannot inadvertently add more records.

    When the user clicks a button to generate the Report or other outputs based on this date range, the Parameter Sub-Form can be refreshed first to update the values in the table. After that, the query can be executed to reflect the latest StartDate and EndDate values.

  4. The above example retrieves all data between StartDate and EndDate. However, sometimes we need to filter specific, non-sequential values—for instance, Employee Codes 1, 5, 7, and 8. In such cases, we are forced to enter the codes manually in the Criteria row of the query, using one of several methods, as illustrated in the sample image below:

Query Parameter Input Methods.

I would like to share another method I use to let users select parameter values for reports—by simply checking boxes in a Parameter Table.

For example, assume that our company has several branch offices across the country, and management occasionally requests reports for selected branches. Since branch names remain constant, we can enable users to pick the required branches by placing check marks beside them. The check-marked entries can then serve as criteria for filtering data.

To illustrate this method more clearly (and to keep it simple), let’s use a list of months as an example. We will see how the selected months are used as criteria for the main query. The image below shows how this list of months appears to the user in a datasheet form, displayed as a subform on the main form.

We will need two queries for this process—one to filter the selected months from the list, and a second (the main query) that uses the results of the first query as parameters to filter data for the report.

The first query should return the values 3, 6, 9, and 12, based on the month selections shown in the image above. The following SQL statement can be used to achieve this result:

Query Name: Month_ParamQ

SELECT Month_Parameter.MTH
FROM Month_Parameter
WHERE (((Month_Parameter.[SELECT])=True));

When the user selects or deselects check marks on the parameter screen, these changes may not update in the underlying Month_Parameter table. To ensure the latest selections are reflected, we must refresh the Month_Parameter subform before opening the report that retrieves data from the main query (which uses the above query as its criteria).

To handle this, include the following statement in the On_Click() event procedure of the Print Preview command button:

Private Sub cmdPreview_Click()
     Me.Month_Parameter.Form.Refresh
     DoCmd.OpenReport "myNewReport", acViewPreview
End Sub

Now, how can the selected months filtered in the Month_ParamQ be used in the Main Query as a criterion? The third method we used earlier as a criterion in the first Image given above. I will repeat it below:

IN(1,5,7,8)

Here, we will compare the EmployeeID values with the numbers 1, 5, 7, 8, and select records that match any of these numbers as output.

Similarly, all we need to do here in the Main Query is to write this as a Sub_Query in the Criteria Row to use the Month Values from the Month_ParamQ. The above criteria clause, when written in the form of a sub-query, will look like the following:

IN(SELECT MTH FROM MONTH_PARAMQ)

The User doesn't have to type the Report Parameter values; they can select required items from a list, click a Button, and the Report is ready.

Share:

Form Menu Bars and Toolbars

Form Menu Bars and Toolbars.

During the development of a database, most of our time is spent creating tables, defining relationships, designing forms and reports, and planning process steps that transform raw data into meaningful reports, helping users make timely, informed decisions. Microsoft Access provides a wide range of menus and toolbars that make these design tasks relatively easy.

Once development nears completion, our focus shifts to security and usability—specifically, how users will interact with the database in their daily operations and what actions they should or should not perform. We want to prevent users from tampering with forms, reports, or other design elements and unintentionally disrupting the system.

By properly implementing Microsoft Access security features, we can control what each user or group is allowed to do. Additionally, removing the default menu bars and toolbars—and replacing them with custom menus and toolbars tailored to user needs—helps ensure a clean, intuitive interface for everyday use.

The Form/Report-Property Sheet.

When you open a Form or Report in Normal View, certain settings on the Form/Report's Properties influence the display of Menus or Toolbars associated with them. An image of the Form's Property Sheet is given below:

When you click the drop-down arrow in the Menu Bar property, a list of all custom menu bars you have created (or imported from another database) will appear. You can select the desired menu bar from this list to assign it to the form. Similarly, you can specify custom toolbars and shortcut menu bars in their respective property fields.

You can also enable or disable a form’s shortcut menu by setting its Shortcut Menu property to Yes or No, respectively.

When the form is opened in Normal View, the assigned custom menus and toolbars will automatically appear according to the property settings.

NB: You can go through the following Posts to learn more about designing Custom Menus and Toolbars:

Automating Menus/Toolbars Settings.

When your database contains numerous Forms and Reports, opening each one individually in Design View to set these properties manually can quickly drain the enthusiasm you had while building the database. Fortunately, this tedious task can be automated with a simple VBA routine.

This routine can scan the entire database in less than a minute, updating all Forms and Reports by assigning the specified Custom Menu Bar and Tool Bar names to their corresponding properties automatically.

Simply copy and paste the following VBA code into a global module in your database, and then save the module.

Public Function MenuToolbarSetup()
'-----------------------------------------------------------
'Author : a.p.r. pillai
'Date   : September, 1998
'URL    : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------------
Dim ctr As Container, doc As Document
Dim docName As String, cdb As Database
Dim msg As String, msgbuttons As Long

On Error GoTo MenuToolbarSetup_Err

Set cdb = CurrentDb
Set ctr = cdb.Containers("Forms")
msgbuttons = vbDefaultButton2 + vbYesNo + vbQuestion
' Set MenuBar, toolbar properties of Forms
msg = "Custom Menus/Toobar Setup on Forms. " & vbCr & vbCr _& "Proceed...?"
If MsgBox(msg, msgbuttons, "MenuToolbarSetup()") = vbNo Then
   GoTo NextStep
End If
For Each doc In ctr.Documents
  docName = doc.Name  
'Open the Form in Design View and hidden mode   
DoCmd.OpenForm docName, acDesign, , , , acHidden
   With Forms(docName)
     .MenuBar = "MyMainMenu"
     .Toolbar = "MyMainToolBar"
     .ShortcutMenu = True
     .ShortcutMenuBar = "MyShortCut"
   End With  
'Save and Close the Form after change
   DoCmd.Close acForm, docName, acSaveYes
Next

NextStep:
'MenuBar,Toolbar properties of Reports
msg = "Custom Menus/Toobar Setup on Reports. " & vbCr & vbCr _& "Proceed...? "

If MsgBox(msg, msgbuttons, "MenuToolbarSetup()") = vbNo Then
   GoTo MenuToolbarSetup_Exit
End If

Set ctr = cdb.Containers("Reports")
'Reports cannot be opened in hidden mode
For Each doc In ctr.Documents
 docName = doc.Name
 DoCmd.OpenReport docName, acViewDesign
 Reports(docName).MenuBar = "MyMainMenu" 
Reports(docName).Toolbar = "MyReportToolBar" 
DoCmd.Close acReport, docName, acSaveYes
Next

msg = "Custom Menus/Toobar Setup Completed successfully. "

MsgBox msg

Set ctr = Nothing
Set cdb = Nothing

MenuToolbarSetup_Exit:
Exit Function

MenuToolbarSetup_Err:
MsgBox Err.Description
Resume MenuToolbarSetup_Exit
End Function

Run the Code from the Debug Window

Since this is purely a design-time task, you can execute the code directly by placing the cursor anywhere within the procedure and pressing the F5 key, or by calling it from the On_Click() event of a Command Button on a form.

However, remember that this form (the one containing the command button) will also be opened in Design View when the code runs to update property values. If you want to prevent that from happening, include an If...Then condition in your code to bypass this form.

Share:

Seriality Control Finding Missing Numbers

Seriality Control: Finding Missing Numbers.

In accounting and auditing, it is a standard practice to maintain strict control over the use of important documents such as checkbooks, receipt vouchers, payment vouchers, and local purchase orders. The usage of these documents is closely monitored to prevent misuse that could negatively impact the company’s operations or reputation.

These documents are usually printed in books containing 20, 50, or 100 sheets, each bearing sequential serial numbers. All transactions involving these documents are recorded along with their corresponding serial numbers.

Periodic audits are conducted to verify that the serial numbers recorded in the system match the continuity of used documents in hand. Any missing numbers, whether due to cancellation, loss, or other reasons, are investigated and properly documented.

To illustrate this process, we’ll create a sample program that identifies and lists missing serial numbers from recorded transactions. For this, we’ll need the following tables containing the necessary information:

Preparing for Trial Run

  1. Parameter Table: with Start-Number and End-Number values. Uses this number range to find the missing numbers from within the Transaction Table.

  2. Transaction Table: where the actual transaction details of the Documents are recorded, and our program should check and bring out the missing cases.

  3. Missing_List Table: where the missing list of Numbers will be created.

  4. Copy the following VBA Code and paste it into a new Global Module in your Database.

The VBA Code

Option Compare Database
Option Explicit

Type Rec
    lngNum As Long
    flag As Boolean
End Type

Public Function MissingNumbers()
'------------------------------------------------------
'Author : a.p.r. pillai
'Date   : 05/10/2008
'URL    : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------
Dim db As Database, rst1 As Recordset, rst2 As Recordset
Dim lngStart As Long, lngEnd As Long
Dim ChequeNo As Long, j As Long, ChqSeries() As Rec
Dim NumberOfChqs As Long, k As Integer, bank As String
Dim strSeries As String

On Error GoTo MissingNumbers_Err

'initialize the Report Table
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE Missing_List.* FROM Missing_List;"
DoCmd.SetWarnings True

Set db = CurrentDb
'Load Cheque Book Start and End Numbers
'from parameter table
Set rst1 = db.OpenRecordset("Parameter", dbOpenDynaset)
Do While Not rst1.EOF
    bank = rst1!bank
    lngStart = rst1!StartNumber
    lngEnd = rst1!EndNumber
' calculate number of cheques
    NumberOfChqs = lngEnd - lngStart + 1
    strSeries = "Range: " & lngStart & " To " & lngEnd

'redimention array to hold all the cheque Numbers
'between Start and End numbers
    ReDim ChqSeries(1 To NumberOfChqs) As Rec

'Generate All cheque Numbers between
'Start and End Numbers and load into Array
    k = 0
    For j = lngStart To lngEnd
        k = k + 1
        ChqSeries(k).lngNum = j
        ChqSeries(k).flag = False
    Next

'Open Cheque Payment Transaction Records
    Set rst2 = db.OpenRecordset("Transactions", dbOpenDynaset)

'Flag all matching cheque Numbers in Array
    k = 0
    rst2.MoveFirst
    Do While Not rst2.EOF
        ChequeNo = rst2![chqNo]
        If ChequeNo >= lngStart And ChequeNo <= lngEnd And rst2![bnkCode] = bank Then
            j = (ChequeNo - lngStart) + 1
            ChqSeries(j).flag = True
        End If
        rst2.MoveNext
    Loop
    rst2.Close

'create records for unmatched items in Report Table
    Set rst2 = db.OpenRecordset("Missing_List", dbOpenDynaset)
    k = 0
    For j = lngStart To lngEnd
        k = k + 1
        If ChqSeries(k).flag = False Then
            With rst2
                .AddNew
                !bnk = bank
                ![MISSING_NUMBER] = ChqSeries(k).lngNum
                ![REMARKS] = "** missing **"
                ![CHECKED_SERIES] = strSeries
                .Update
            End With
        End If
    Next
    rst2.Close

rst1.MoveNext
Loop
rst1.Close

Set rst1 = Nothing
Set rst2 = Nothing
Set db = Nothing

MissingNumbers_Exit:
Exit Function

MissingNumbers_Err:
MsgBox Err & " : " & Err.Description, , "MissingNumbers()"
Resume MissingNumbers_Exit
End Function

To try out the above program, create the first two tables with the same Field Names and data type as suggested by the sample data given above, and enter the same data or similar records of your choice, excluding some serial numbers from the range of values in the Parameter Table.

Create the third Table (Missing_List) with the same Field Names and data type of the sample records shown above, but without adding any records to it.

VBA Code Analysis

In the global area of the Module, we have created a User-Defined Data Type Rec with two elements, lngNum to hold the Serial Number and Flag to mark when a match is found in the Transaction Table, with Long Integer and Boolean data types, respectively. After creating the new data type in the Global area, we have declared an empty array variable ChqSeries() as Rec with the newly created data type within the Program.

The program opens the Parameter Table, starts with the first record, calculates the number of records that come within the given range, and re-dimensions the array to hold all the numbers between the lngStart and lngEnd parameter values.

In the next step, the program generates all the serial numbers between lngStart and lngEnd and fills the chqSeries().lngNum array. The Flag element value is set as False.

Next, open the Transaction Table and scan through it for matching Bank Code and for Cheque Numbers between lngStart and lngEnd, and when a match is found, the 'chqSeries().Flag' is marked as True for that entry within the array, and continues this process till the end of the file is reached.

In this process, if the 'chqSeries().Flag' is not marked as True, then the Serial Number corresponding to that entry is found missing in the Transaction Table. In the next step, we scan through the Array and check for entries with 'chqSeries().Flag' = False, and write them out in the Missing_List.

This process continues for all the records in the Parameter Table.

Note: This method is not the most efficient in terms of processing speed when handling a large volume of transactions. In such cases, it is advisable to filter the data in the Transaction table using a parameterized query and use the filtered dataset in place of the full Transaction table.

This needs extra steps in the program to create a Dynamic Query with SQL Statement just before the following statement: Set rst2 = db.OpenRecordset("Transactions", dbOpenDynaset), replacing Transactions with the Query name.

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