Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Macros and Temporary Variables

If you are using Microsoft Access 2007 then there is something new for you. You can use the SetTempVar action in Macros to define Global Variables.  After that you can use the values in those variables in another macro or in an event procedure or on Forms or Reports. The temporary variables remain in memory till you clear them with the RemoveTempvar macro action or remove all the variables with RemoveAllTempVars macro action . All variables will be cleared from memory when you close the database.

Let us try a quick example to understand the usage in macro:

  1. Select Macros from the Create Menu.
  2. Select SetTempVar Action in the first row.
  3. Type myName in the Name argument.
  4. Type the expression Inputbox(“Type your Name”) in the expression argument.
  5. Save the Macro with a name (say macDefineVar).
  6. Right-click on the macro and select Run from the shortcut menu (or Double-click) to execute the Macro.  The Inputbox() Function will run and will prompt for a value to type.
  7. Type your name and click the OK Command Button.

    Your name is stored in the Variable myName. We have used the Function InputBox() in the expression argument.  You can use constant values, functions or expressions to assign values to the variable myName.

  8. Open a new form in design view.
  9. insert a Text Box in the details section of the Form.
  10. Type the expression =Tempvars!myName in the Control Source property.
  11. Change the form from Design view to Form View.

Your name will be displayed in the text box.  The above example shows how to define a temporary variable and how to reference it in expressions on a Form.  Let us learn how to remove this variable from memory.

  1. Close the Form.
  2. Select Macro from Create menu to open up a new macro in design view.
  3. Select RemoveTempvar from the Action list.
  4. Type myName in the Name parameter.
  5. Save the macro with the name macRemoveVar.
  6. Double-Click on the macRemoveVar macro to execute it.
  7. Open the Form again to check whether your name still appears on the text box on the form or not.

The text box will be empty indicating that the variable myName is gone from memory.  The RemoveTempvar action needs a variable name as parameter.

Let us do something better than this and more useful in real world solutions.  Let us calculate the Order-wise Percentage on the sum of Orders Quantity.  We have worked on this problem earlier in the blog post: Percentage on Total Query.  What we need here mainly is the sum of Orders' Quantity to calculate individual order percentage.  In the earlier example we have used a separate Query to calculate the sum of Orders and linked with a second Query on Order Number to calculate the percentage.

Here we will initialize a Temporary Variable with the sum of Quantity and use the Variable name in the percentage calculation expression.

  1. Import the Order Details table from Northwind.accdb sample database.
  2. Select Query Design from Create menu; don't select any table or query from the displayed list.
  3. Change the Query into SQL view; copy and paste the following SQL string and save the Query with the name OrderPercentageQ:
    SELECT [Order Details].OrderID, First([Order Details].UnitPrice) AS UnitPrice, Sum([Order Details].Quantity) AS Quantity
    FROM [Order Details]
    GROUP BY [Order Details].OrderID;
  4. Open the macro macDefineVar in design view.
  5. Change the variable name myName to TotalQuantity (myName variable will remain in memory).
  6. Change the expression InputBox(“Enter your Name”) to DSum(“Quantity”,”[Order Details]”).  Do not add the = symbol at the beginning of the expression.  Save the macro with the change.
  7. Double-click on the macro to run and calculate the total of quantity and store the value into the temporary variable TotalQuantity.

    We will modify the OrderPercentageQ with the addition of a new column that calculates the order-wise percentage on total orders.

  8. Open a new Query in SQL View.
  9. Copy and Paste the following SQL String into the SQL editing window of the new Query and save it with the name OrderPercentageQ2:
    SELECT [Order Details].OrderID, First([Order Details].UnitPrice) AS UnitPrice, Sum([Order Details].Quantity) AS Qty, Sum([quantity])/[tempvars]![totalQuantity]*100 AS Percentage
    FROM [Order Details]
    GROUP BY [Order Details].OrderID;
  10. Open the Query in Design View and check how we have written the expression in the last column to calculate the percentage using the temporary variable [tempvars]![totalQuantity].
  11. Change the Query View into Datasheet View to display the Order-wise Quantity percentage on Total.

Usage in VBA

We can work with the Temporary Variable (Tempvars Object) in VBA.

With the Add method we can define a Temporary Variable and assign an initial value into it.

Add() method of TempVars Object:

    Syntax: TempVars.Add "Variable Name","Initial Value"

    Example-1: TempVars.Add "TotalQuantity", DSum("Quantity", "[Order Details]")


    Example-2: TempVars!TotalQuantity =  DSum("Quantity", "[Order Details]")

You can define a total of 255 temporary variables in this way. 

Remove method of TempVars Object:

The Remove() method erases only one variable and free the memory occupied by the variable.

    Syntax: TempVars.Remove "Variable Name"

    Example: TempVars.Remove "TotalQuantity"

RemoveAll method of TempVars Object:

The RemoveAll() removes all the temporary variables defined with the Add() method.

    Syntax: TempVars.RemoveAll

    Example: TempVars.RemoveAll

The Count property gives the count of all temporary variables defined in memory:

Example: Debug.Print TempVars.Count returns the count of temporary variables defined in memory

Each temporary variable defined in memory have an index number starting from 0 to the total number of such variables in memory –1.  Each variable can be referenced with the Item index and can be used to read the Name of the variable or its Value or to assign new values into the variable.

Debug.Print TempVars.Item(0).Name prints the name of the variable.

SumofQuantity = TempVars.Item(0).Value

You can also use this reference to modify the existing value in the temporary variable.

TempVars.Item(0).Value = TempVars.Item(0).Value + 1

You should not use a subscript beyond the existing number of temporary variables in memory otherwise an error will occur.  If you have defined 5 variables then the valid index numbers are 0 to 4.


1 comment:

  1. [...] LEARN MS-ACCESS TIPS AND TRICKS – Macros and Temporary Variables Apr 2, 2011 … Alerts & Animations, 3D text wizard, graph charts, … Animations. MsgBox with Office Assistant ….. a.p.r.pillai Says: Download a sample database with all the running pr. … [...]



Subscribe in a reader
Your email address:

Delivered by FeedBurner


Popular Posts

Search This Blog

Blog Archive

Powered by Blogger.


Forms How Tos Functions MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Queries External Links msaccess reports msaccess tips Accesstips Array Menus and Toolbars MsaccessLinks Process Controls Art Work Class Module Downloads msaccess How Tos Graph Charts Objects msaccessQuery Combo Boxes List Boxes Property VBA Collection Object Command Buttons Data Emails and Alerts Query Calculation Custom Wizards DOS Commands Data Type Dictionary Object ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Object Reference msaccessprocess security advanced Access Security Add Controls Custom Functions Field Type Form Form Instances Item Key Macros Menus Report Top Values Variables msaccess email msaccess menus progressmeter Access2007 Auto-Number Copy Event Expression Fields Join Methods Microsoft Numbering System Records Recordset Security Split SubForm Table Time Difference Utility WithEvents Workgroup Wrapper Classes database msaccess wizards tutorial Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Conditional Formatting Data Filtering Defining Pages Diagram Disk Dynamic Lookup Error Handler Excel Export External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Monitoring Octal Numbers Operating System Paste Primary-Key Product RaiseEvent Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Tables Union Query User Users Water-Mark Word automatically commands function hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code

Featured Post

WithEvents and Defining your own Events

Hope that you have gone through last week’s WithEvents, Event, RaiseEvent introduction, tried out the sample Forms and understood as how bo...


Blog Archive

Recent Posts