Fix an Excel VBA For Loop That Does Not Execute
Question details
Correct a VBA For loop so it can process data from multiple worksheets.

- Product
- Microsoft Excel VBA
- Device & OS
- not provided
- Scenario
- A macro needs to copy data from multiple worksheets, potentially excluding a main sheet.
- Observed behavior
- The loop body does not execute because the worksheet count is compared with -1 instead of being reduced by 1.
Identify which workbook and worksheets the macro should process, including whether the main sheet is first or last. Open the workbook containing the macro in Excel.
Correct the Worksheet Count in the VBA Loop
Use a numeric worksheet count as the loop limit instead of an equality comparison.
The expression Worksheets.Count = -1 is a comparison. It evaluates to False, which is treated as 0 in this loop, so a loop starting at 1 has no iterations.
In Excel, open the Developer tab and select Visual Basic, then open the module containing the macro.
If the last worksheet should be excluded, replace the loop header with For i = 1 To ThisWorkbook.Worksheets.Count - 1. ThisWorkbook refers to the workbook containing the macro.
If the first worksheet is the main sheet and all remaining sheets should be processed, use For i = 2 To ThisWorkbook.Worksheets.Count instead. Make sure the worksheet references inside the loop use the same workbook.
Click inside the macro and press F8 in the VBA editor to step through it. Check that the loop enters its body and processes the intended worksheets.

Work with Excel Spreadsheets in WPS Office
WPS Office is a free, lightweight alternative for working with spreadsheets in a familiar interface. Open compatible Excel files to make migration easier; fixing and running an Excel VBA macro may require Microsoft Excel or a WPS version with suitable VBA support.

Frequently Asked Questions
Why does Worksheets.Count = -1 make the loop skip?
It compares the worksheet count with -1 instead of subtracting 1. The comparison returns False, treated as 0, so a For loop starting at 1 does not enter its body.
How do I skip the first worksheet in the loop?
In the VBA editor, use For i = 2 To ThisWorkbook.Worksheets.Count. This processes the second through last worksheets in the workbook containing the macro.
How do I exclude the last worksheet instead?
Use For i = 1 To ThisWorkbook.Worksheets.Count - 1 as the loop header. Check the sheet order in Excel first to ensure the last sheet is the one you want to exclude.
What if the worksheets are in a different workbook?
Replace ThisWorkbook with a reference to the intended open workbook, such as Workbooks("Data.xlsx"), and use that same workbook reference when accessing sheets inside the loop.




