Fix an Excel VBA For-Next Loop When Copying Data
Question details
Correct a VBA loop that copies matching records between Excel worksheets.

- Product
- Microsoft Excel VBA
- Device & OS
- not provided
- Scenario
- A macro scans source rows and copies matching records to another worksheet.
- Observed behavior
- The copied data appears briefly and then disappears, while the loop counter is modified inside the For-Next loop.
Open the workbook and locate the macro that copies the records. Check which source rows should be processed and how the variable last is calculated.
Use a Step value instead of changing the loop counter
Use Step 3 when the macro should process every third row, starting at row 4.
In Excel, open Developer > Visual Basic, then find the procedure that copies the matching records.
Replace For j = 4 To last with For j = 4 To last Step 3. Keep the existing matching and copying statements inside the loop.
Delete the j = j + 2 statement inside the loop, and leave Next j in place. The For-Next loop will advance j by three on each iteration.
Run the macro or use Debug > Step Into in the Visual Basic editor. Confirm that j visits rows 4, 7, 10, and so on, up to last, and check the destination worksheet.

Work with Excel spreadsheets in WPS Office
WPS Office is a free, lightweight alternative for viewing and editing spreadsheets in a familiar interface. Open compatible Excel files to move routine spreadsheet work to WPS; fixing an Excel VBA macro still requires checking the macro in Excel.

Frequently Asked Questions
Why should I avoid changing j inside a For-Next loop?
For-Next controls the counter using the loop's Step value. Changing j inside the loop makes the rows visited harder to predict and can cause records to be skipped.
Which rows does For j = 4 To last Step 3 process?
It processes rows 4, 7, 10, and so on, stopping before j exceeds last. Check the calculation of last in the macro to confirm the intended range.
What if I need to process every row instead?
Use For j = 4 To last without Step 3 and remove the separate j = j + 2 statement. The default step is 1.
What should I check if copied data still disappears?
In the Visual Basic editor, use Debug > Step Into and inspect the destination worksheet as the macro runs. Look for later statements that clear the range or write new data over it.




