Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
551 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Software ==> | Excel VBA Macros (52 exercises) |
Topic ==> | Looping over collections (11 exercises) |
Level ==> | Average difficulty |
Subject ==> | VBA training |
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.
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).
To do this, 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:
With Sheet1.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("B3:G3")
.SetRange Range("B3:G3")
.Orientation = xlLeftToRight
.Apply
End With
Save and close the workbook.
You can find other training resources for the subject of this exercise here:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.