Compile Error - Invalid next control reference. Please tell me what 'm doing wrong...

pedie

Well-known Member
Joined
Apr 28, 2010
Messages
3,875
Compile Error - Invalid next control reference. Please tell me what 'm doing wrong...

Thanks in advance :)

Code:
[FONT=Courier New]Option Explicit[/FONT]
[FONT=Courier New]Sub test2()[/FONT]
[FONT=Courier New]Dim i, j As Integer
Dim lr, lr2 As Long[/FONT]
[FONT=Courier New]lr = Sheets("Jan").Cells(Rows.Count, "A").End(xlUp).Row
lr2 = Sheets("Feb").Cells(Rows.Count, "A").End(xlUp).Row[/FONT]
[FONT=Courier New]For i = 1 To lr
For j = 2 To lr2
 Debug.Print Cells(i, "A")
 Debug.Print Cells(j, "A")[/FONT]
[FONT=Courier New]Next i
Next j[/FONT]
[FONT=Courier New]End Sub[/FONT]
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
Your loops are not nested correctly. It works on a LIFO (or FILO) basis, i.e. Last In First Out or First In Last Out:
Rich (BB code):
For i = 1 to x
   For j = 1 to y

   Next j
Next i
Check where your i loop ends and your j loop ends
 
Upvote 0
pedie,

Your looping is not correct.


Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).


Rich (BB code):
Option Explicit
Sub test2()
Dim i As Long, j As Long
Dim lr As Long, lr2 As Long
lr = Sheets("Jan").Cells(Rows.Count, "A").End(xlUp).Row
lr2 = Sheets("Feb").Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To lr
  For j = 2 To lr2
   Debug.Print Sheets("Jan").Cells(i, "A")
   Debug.Print Sheets("Feb").Cells(j, "A")
  Next j
Next i
End Sub
 
Upvote 0
Thanks alot everyone! really appriciate that....
yea, it has to be next j then next i ....thanks again:)
 
Upvote 0

Forum statistics

Threads
1,224,583
Messages
6,179,673
Members
452,937
Latest member
Bhg1984

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