Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Sunday, April 3, 2011

Macros and Temporary Variables

Introduction.

If you are using Microsoft Access 2007 or a later version, there is a useful new feature: the SetTempVar action in Macros, which allows you to define global variables. Once defined, these variables can be used across other macros, event procedures, forms, or reports. The temporary variables remain in memory until you explicitly clear them using the RemoveTempVar action (for a single variable) or the RemoveAllTempVars action (to clear all). All temporary variables are automatically removed from memory when you close the database.

The TempVar Usage in Macros.

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 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 the 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 now appear in the text box. The above example demonstrates how to define a temporary variable and reference it in expressions on a form. Next, let us see how to remove this variable from memory.

  12. Close the Form.

  13. Select Macro from the Create menu to open up a new macro in the design view.

  14. Select RemoveTempvar from the Action list.

  15. Type myName in the Name parameter.

  16. Save the macro with the name macRemoveVar.

  17. Double-click on the macRemoveVar macro to execute it.

  18. Open the form again to check whether your name still appears in the text box on the form or not.

The text box will be empty, indicating that the variable myName does not exist in memory.  The RemoveTempvar action needs a variable name as a parameter.

TempVar Usage in Query.

Let us take this a step further and build something more practical for real-world scenarios. This time, we will calculate the order-wise percentage based on the total Order quantity. We explored a similar problem earlier in the blog post Percentage in Total_Query.

The key requirement here is to obtain the sum of all order quantities to calculate the percentage for each individual order. In the earlier example, we accomplished this by creating a separate query to calculate the total order quantity and then linking it with a second query, grouped by Order Number, to compute the percentages.

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 the Northwind sample database.

  2. Select Query Design from the Create menu; don't select any table or query from the displayed list.

  3. Change the Query in 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 the 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 quantity and store the value in the temporary variable TotalQuantity.

    We will modify the OrderPercentageQ with the addition of a new column that calculates the order-wise percentage of 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 percentage of Total Quantity.

The TempVar 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 to it.

Add() method of TempVars Object:

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

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

    OR

    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 frees the memory occupied by the variable.

    Syntax: TempVars.Remove "Variable Name"

    Example: TempVars.Remove "TotalQuantity"

RemoveAll method of TempVars Object:

The RemoveAll() method 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

TempVars Item Indexes.

Each temporary variable stored in memory is assigned an index number, starting from 0 up to (total number of variables – 1). A variable can be referenced by its Item index, which allows you to read its Name or Value, or even assign a new value to it. The 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.

Earlier Post Link References:

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. … [...]

    ReplyDelete

Comments subject to moderation before publishing.

Powered by Blogger.