Link to home
Start Free TrialLog in
Avatar of Noah
NoahFlag for Singapore

asked on

Needs Help with a Nested "FOR.. NEXT" Loop

Hi everyone! I am trying to write a nested “FOR… NEXT” loop to create the following table in Excel

User generated image
Any help is much appreciated! :)
Avatar of Alan
Alan
Flag of New Zealand image

Not sure what the reading night be, but it would be trivial with a formula.

Why VBA?


Alan
ASKER CERTIFIED SOLUTION
Avatar of Subodh Tiwari (Neeraj)
Subodh Tiwari (Neeraj)
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
*reason might*

Editing stopped working on mobile for me a while ago :-(
Avatar of Noah

ASKER

Hi Alan! I am actually learning how to use vba and I posted this so that I can get an example as reference :)
In that case, there is so much to learn for you in the code I posted.
Avatar of Noah

ASKER

I guess it's alright! then. Thank you for all of your help! :)
Avatar of Noah

ASKER

Hi all! I will be leaving this question open for a while longer if anyone has any alternative codes :)
In that case, I'd say the code above is just about exactly what you want.

Alan.
Avatar of Bill Prew
Bill Prew

And since you asked about nested loops, here's an approach that shows that, iterating over each row in the range, and within each row looks at each column one by one.

Sub PopulateRangeWithOddEven()
    Dim rng As Range
    Dim r As Long
    Dim c As Long
    
    Set rng = Range("A1:G10")

    rng.ClearContents

    For r = 1 To rng.Rows.Count
        For c = 1 To rng.Columns.Count
            Select Case (r And 1) + (c And 1)
                Case 2
                    rng.Cells(r, c) = "Odd"
                Case 0
                    rng.Cells(r, c) = "Even"
            End Select
        Next
    Next

End Sub

Open in new window


»bp
I am trying to write a nested “FOR… NEXT” loop
Try this:
Sub Fill_Odd_Even()
    Dim r As Range
    Dim ri As Long
    Dim ci As Long
    Dim rmax As Long
    Dim cmax As Long
    
    Set r = Range("A1:W23")
    rmax = r.Rows.Count
    cmax = r.Columns.Count
    For ri = 1 To rmax Step 2
        For ci = 1 To cmax Step 2
            Cells(ri, ci).Value = "Odd"
            If ri + 1 > rmax Or ci + 1 > cmax Then
            Else
                Cells(ri + 1, ci + 1).Value = "Even"
            End If
        Next ci
    Next ri
    
End Sub

Open in new window