Excel VBA Macros | Looping over collections exercise | Split list of dinosaurs onto separate sheets

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.

Software ==> Excel VBA Macros  (52 exercises)
Version ==> Any version of Excel
Topic ==> Looping over collections  (11 exercises)
Level ==> Average difficulty
Subject ==> VBA training
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 file called Dino List.xlsx from the folder shown above.

Your task is to split the main list of dinosaurs into three separate sheets based on the value of the Diet column:

Worksheet names

You need to copy rows from the Dino List sheet into the appropriate worksheet.


Start by writing a For Each loop to loop over the list of dinosaur names in column A of the Dino List sheet.  You'll need at least one Range variable to do this.

Declare a String variable and add a line inside the For Each loop which captures the diet of the current dinosaur.  You can Offset from the cell that is referenced by the Range variable to do this.

Copy the current dinosaur's data into the appropriate worksheet.  You can do this in a variety of ways but one simple approach would be to:

  1. Copy the current row of data (use the Range variable rather than the ActiveCell).
  2. Select the worksheet whose name matches the dinosaur's diet.
  3. Find the next blank row in the worksheet, for example:

Range("A1048576").End(xlUp).Offset(1, 0).Select

  1. Paste the copied data at this cell.

Add a new line after the For Each loop which copies the column headings from the Dino List sheet.

Declare a Worksheet variable and add a new For Each loop at the bottom of the procedure which loops over the Worksheets collection.

Inside the new loop, add code which pastes the copied column headings into the first row of each worksheet except for the Dino List sheet.

Include a line inside the loop which changes the width of the columns to fit the data they contain.

Final result

This is what you should see on the Omnivore sheet.


As a final flourish, you could add a separate subroutine which clears the three diet worksheets and call this at the start of your main procedure.

Save and close the workbook.

You can unzip this file to see the answers to this exercise, although please remember this is for your personal use only.
This page has 0 threads Add post