How to make an action optional

Bale626

New Member
Joined
Sep 20, 2024
Messages
2
Office Version
  1. 365
Platform
  1. Windows
VBA Newbie here; I have built a macro to copy data from one spreadsheet to another, compiling multiple sheets from the source workbook into a single sheet in the target workbook. However, the report that spits out the source workbook does not always have the same number of sheets. Is there a way in VBA to make a set of actions optional?

To further explain, the source workbook will nominally have 15 sheets to pull data from. However, if it has less, it will throw up an error and stop the rest of the macro from running. I need a way to make the steps of the individual sheets optional, so if the source workbook only has 13 sheets, it will skip steps 14 & 15 and finish running the macro.
 

Excel Facts

Pivot Table Drill Down
Double-click any number in a pivot table to create a new report showing all detail rows that make up that number
Hello,

Well if the initial workbook has a variable amount of sheets, you can use the Workbook.Worksheets.Count property (Excel) | Microsoft Learn property to iterate over the variable quantity of sheets of the workbook. Alternatively you can use a For Each...Next statement (VBA) | Microsoft Learn.

On a more general matter you can use the On Error statement (VBA) | Microsoft Learn to handle expected errors in the code, but it is considered a better practice to just avoid raising errors if possible.
 
Upvote 0

Forum statistics

Threads
1,222,625
Messages
6,167,146
Members
452,099
Latest member
Auroraaa

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top