VBA question from a complete noob

Samurai

New Member
Joined
Jun 15, 2011
Messages
17
Hey everyone,

I have just started learning VBA and I was practicing creating some very simple sub procedures. The procedure below inserts random numbers in a range that is 5 cells wide and 5 cells long:

Code:
Sub RandomCodeThatWorks()
Dim c As Double
Dim r As Double
    For r = 1 To 5
    For c = 1 To 5
        Cells(r, c) = Rnd
[B][COLOR=DarkGreen]    Next c
Next r[/COLOR][/B]
End Sub
Now here's what's driving me crazy. If I say Next r before Next c like in the next code, I get "Invalid Next control variable reference".

Code:
Sub RandomCodeDoesNotWork()
Dim c As Double
Dim r As Double
    For r = 1 To 5
    For c = 1 To 5
        Cells(r, c) = Rnd
[B] [COLOR=DarkRed]   Next r
Next c[/COLOR][/B]
End Sub
I was trying to figure out why this error occurs.

It appears that the variable order must be different in the For statement and the Next statement.

I have no idea why this is happening. I would really appreciate if someone could explain. Thanks!
 

Excel Facts

Who is Mr Spreadsheet?
Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.
Welcome to the MrExcel board!

That's just how 'For...Next' loops work. They need to nest one inside the other or be completely separate, they cannot overlap as in your second example.
 
Upvote 0
You have to finish one nested loop before you exit to the higher one.
i.e.

Code:
For i = 1 to 5
     For j = 1 to 5
          For k = 1 to 5
               .....your code....
          Next k
     Next j
Next i
 
Last edited:
Upvote 0
Now it makes sense! Thanks a lot Peter and Roli001.

Just shows that using indentation when nesting can make things a lot clearer.
 
Upvote 0

Forum statistics

Threads
1,224,574
Messages
6,179,633
Members
452,933
Latest member
patv

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