VBA Random Number with no Duplicates

mdmxq6

New Member
Joined
Jan 27, 2014
Messages
2
I have a question regarding some VBA code I am using to generate random numbers. In a varying range, I want the code to generate a random number, and then check all previous ranges to ensure there are no duplicates. When I run the code step by step, I can see that it sometimes work. I.e. The code will generate a random number, but that number already exists, so it generates a new random number replace it, check again, etc. However, sometimes it will produce a duplicate number and NOT run the code again to replace it. I have no idea why! Any help would be appreciated!

I am using Excel 2010, VBA 7.0

RecipeRows = Input Box based on number of random numbers the user wants
TotalRecipes = A count of used rows in a different sheet


Code:
For Each c In Range("A3:A" & RecipeRows)
TryAgain: c.Value = (Int((TotalRecipes * Rnd) + 1))
If Not Range("A3:A" & c.Row - 1).Find(c.Value, LookIn:=xlValues) Is Nothing Then GoTo TryAgain
Next c
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
The third line of code above should read Range("A2:A"" & c.Row - 1) If A3 is entered the code will continuously loop.
 
Upvote 0

Forum statistics

Threads
1,214,911
Messages
6,122,194
Members
449,072
Latest member
DW Draft

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