WISE OWL EXERCISES
EXCEL VBA MACROS EXERCISES
Excel VBA Macros | Looping over collections exercise | Generate Random Lottery Numbers
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 one of more of the courses listed below!
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 file called Lucky Dip.xlsx and create a subroutine to generate a set of random lottery numbers.
You need to create 6 random numbers between 1 and 59 (they don't need to be in order).
Start by looping over the six cells that you need to populate using a For Each loop.
Inside the loop, add a line which generates a random number between 1 and 59 and captures it in a variable. You can use the RandBetween function to do this:
Num = WorksheetFunction.RandBetween(1, 59)
Add a line to write the number in the variable into the cell that the loop is pointing to, then run the subroutine a few times to test it.
One problem is that you might generate the same number multiple times.
Add a Do Loop structure around the line which calculates a random number. Add a condition to this loop so that it continues Until it generates a number that isn't already in the worksheet.
You could use the Find method and check that its result Is Nothing to establish that the number isn't already in the worksheet.
Add a line at the start of the subroutine which clears the contents of the cells you're looping over.
If you'd like to see your numbers sorted, you could add the code shown below:
.Orientation = xlLeftToRight
Save and close the workbook.