Looping through worksheets is one of the most common actions performed by those who use VBA to automate Excel. However, we don’t always want to apply a macro to every worksheet; sometimes, we only want it for each selected sheet. Depending on the action being performed, this can cause an error.
This occurs where the action can only be performed one sheet at a time. It isn’t a VBA issue; it’s an Excel issue. For example, if you select two worksheets and try to apply worksheet protection, you will notice the option is greyed out.
It can’t be done in Excel; therefore, it’s no surprise it can’t be done in VBA either.
In the code examples below, we will solve this problem. First, we’ll look at how we can loop through the selected sheets. Secondly, we’ll look at using this technique to automate actions that are usually applied one sheet at a time.
Download the example file
I recommend you download the files which support this post, as you’ll be able to work along with examples. This is the best way to learn. You’ll be able to see the solutions in action, plus the file will be useful for future reference. The support files are available for FREE to newsletter subscribers.
Click below to subscribe and gain access to the subscriber area. You will also receive:
- My favorite tips and tricks direct to your inbox
- Exclusive content (which is only available to subscribers)
- FREE tools and downloads
If you’re already a subscriber, click here to log-in to the subscriber downloads area.
The filename for this post is 0030 Loop through selected sheets with VBA.zip.
Loop through selected worksheets
Normally with VBA, we would loop through the worksheets of the ActiveWorkbook, but in this scenario, we want to use the ActiveWindow object instead.
The ActiveWindow has an object called SelectedSheets, which contains an array of… (yes, you’ve guessed it!) the sheets selected. Perfect for our needs.
The following code loops through all the selected worksheets:
Sub LoopThroughSelectedSheets() 'Create variable to hold worksheets Dim ws As Worksheet 'Loop through each selected worksheet For Each ws In ActiveWindow.SelectedSheets 'Perform action. E.g. hide selected worksheets ws.Visible = xlSheetVeryHidden Next ws End Sub
This is the basic code, so you may need to add additional error checks. When hiding worksheets, for example, there must be at least one visible sheet. So, we will either need to count the visible worksheets before commencing or ignore errors. The error checks to be applied will be dependent on your specific requirements.
The macro above works where the action can be performed while other sheets are selected.
Generate accurate VBA code in seconds with AutoMacro
AutoMacro is a powerful VBA code generator that comes loaded with an extensive code library and many other time-saving tools and utilities.
Whether you’re an experienced coder looking to save time, or a newbie just trying to get things to work, AutoMacro is the tool for you.
Applying single worksheet actions with a loop
Since some actions can only be applied one sheet at a time. For these, we need to change our approach. If we were to do this manually, we would:
- Remember which worksheets we had selected
- Apply the action to each sheet individually
- Re-select the same worksheets
Well, that’s exactly what we are going to do, but with VBA.
The comments in the code will help you understand what each line of macro does.
Sub SingleActionWhenLoopingThroughSelectedSheets() Dim ws As Worksheet Dim sheetArray As Variant Dim myPassword As Variant 'Capture the selected sheets Set sheetArray = ActiveWindow.SelectedSheets 'Loop through each selected worksheet For Each ws In sheetArray 'Select the worksheet ws.Select 'Perform action. e.g. Protect each sheet ws.Protect Next ws 'Reselect the sheets sheetArray.Select End Sub
Remember, depending on the action being performed, you may need to add additional error checks.
How to stop the screen flashing?
With VBA, we should perform most actions without selecting or activating anything; it makes the macro more efficient. However, with this solution, that’s not an option. As a result, the screen can flashes while the macro runs. To avoid this, we can change the Application.ScreenUpdating property at the start and end of the macro
Insert the following directly after the Sub has been declared, and before declaring any variables:
Application.ScreenUpdating = False
Insert the following directly before the End Sub statement:
Application.ScreenUpdating = True
Working with chart sheets
In Excel’s mind, chart sheets are not the same as worksheets. So, if you have any chart sheets included in your selection, you may need to make a small alteration to include all sheet types.
Dim ws As Worksheet
Dim ws As Object
So, there you have it. That’s how we loop through selected sheets. It has a few more potential issues than looping through all sheets But, by thinking like a human (you are one after all), we can create a suitable solution.
If you’ve found this post useful, or if you have a better approach, then please leave a comment below.
Do you need help adapting this to your needs?
I’m guessing the examples in this post didn’t exactly meet your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site) you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts: