Exercise: Use DateDiff to calculate years since release

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

The answer to the exercise will be included and explained if you attend the Wise Owl course listed below!

Category ==> Access VBA Macros  (17 exercises)
Topic ==> Creating functions  (2 exercises)
Level ==> Average difficulty
Course ==> Access VBA macros
Before you can do this exercise, you'll need to download and unzip this file (if you have any problems doing this, click here for help).

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Open the module that you have created called modFunctions.

In this module, create a function called YearsSinceRelease which shows the years since a film was released, using the field FilmReleaseDate in the table tblFilm.  There are some notes on how to do this below!

Incorporate this function into a query so that you are displaying films in release date order, with the oldest film first:

Access VBA Macros exercise - Creating functions (image 1)

A sample of the final query - King Kong was released 75 years ago and is the oldest film

To calculate the release date, you need to take the difference between the FilmReleaseDate and today's date.  Here are two functions which may help you:

  • Date() - returns today's date
  • DateDiff("yyyy",EarlierDate,LaterDate) - returns the difference in years between two dates

Note also that you need to surround dates with hashes to test them in the immediate window:

Access VBA Macros exercise - Creating functions (image 2)

Without the hashes, Access would not recognise 1/1/1990 as a date

When you are happy that your function works, save and close the module.

This page has 0 threads Add post