Question

Has anyone found using nested For Each Loops given the named-ranges a hindrance?

Here is a situation I am attempting to make it work, thinking that since named ranges can be helpful (for me) to know which belongs to what.

The requirement of a made-up business has a Program name [named ListofPrograms] which is allocated a colour (has 9), each day [named ListofDates] (over 10 days) an random allocated number of Australian Cows [named ListofCows] (out of 5) are placed in the coloured Program for testing by student vets to demonstrate to their teachers of their academic research and clinical outcomes.

Here the VBA code of how I could have done it. I used the Debug.Print for now as I am not sure how to populate Sheets("Outcome") successfully in this manner.

 Option Explicit
Sub CowsGenerator()
Dim Programrng, Daterng, Cowsrng As Range

With Sheets("Outcome")
    For Each Programrng In Range("ListofPrograms")
            For Each Daterng In Range("ListofDates")
                    For Each Cowsrng In Range("ListofCows")
                        Debug.Print Programrng.Value, Daterng.Value, Cowsrng.FormulaR1C1 = "=RANDBETWEEN(1,5)"
                    Next Cowsrng
            Next Daterng
    Next Programrng
End With
End Sub

Here is the snippet shown in the Immediate Window.

 6             1            False
 6             1            False
 6             2            False
 6             2            False
 6             2            False
 6             2            False
 6             2            False
 6             3            False
 6             3            False

I didn't think False is a good response from RANDBETWEEN and I note it continues from 6 and not from 1.

Any suggestions how I may improve this thanks, Peter.

Was it helpful?

Solution

All your going to get in your immediate window is a check to see if the formulaR1C1 is equal to the string "=RANDBETWEEN(1,5)". I suspect this is not what you need and you wanted a random number between 1 and 5.

Use the following in your debug.print if youneeded to store your value:

Cowsrng.FormulaR1C1 = "=RANDBETWEEN(1,5)"
Debug.Print Programrng.Value, Daterng.Value, Cowsrng.Value

Or if you don't need the value saved:

Debug.Print Programrng.Value, Daterng.Value, Application.workbookfunction.randbetween(1,5)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top