Background
I am able to select values at random from a named range of strings in one sheet ("Sheet2") and populate a column called: MyColumn
in a separate sheet ("Sheet1") using =INDEX(aNamedRange,RANDBETWEEN(1,ROWS(aNamedRange)))
.
It looks like this:
| MyColumn |
|-------------------------------|
| RandomlySelectedValue_1, Col1 |
| RandomlySelectedValue_2, Col1 |
| ... |
| RandomlySelectedValue_N, Col1 |
I have made two other columns: MyColumn2
and MyColumn3
.
Question
As RandBetween
executes upon refresh is there a way to ensure that RandomlySelectedValue_1, Col1
does not equal RandomlySelectedValue_1, Col2?
.
In other words:
- This is the expected behavior, because all the randomly selected strings in the columns are distinct across the same row.
- This is what's happening, there is no check to prevent any randomly selected duplicates in the same row.
What I've tried
I made this VBA Script:
Sub UniqueRandoms()
Do
Worksheets("Sheet1").Range("AB7").Value = WorksheetFunction.Index(Range("FileName.xls!aNamedRange"), WorksheetFunction.RandBetween(1, Sheets("Sheet2").Rows(Range("FileName.xls!aNamedRange"))))
Worksheets("Sheet1").Range("AC7").Value = WorksheetFunction.Index(Range("FileName.xls!aNamedRange"), WorksheetFunction.RandBetween(1, Sheets("Sheet2").Rows(Range("FileName.xls!aNamedRange"))))
Worksheets("Sheet1").Range("AD7").Value = WorksheetFunction.Index(Range("FileName.xls!aNamedRange"), WorksheetFunction.RandBetween(1, Sheets("Sheet2").Rows(Range("FileName.xls!aNamedRange"))))
Exit Do
Loop Until Worksheets("Sheet1").Range("AB7").Value <> Worksheets("Sheet1").Range("AC7").Value And Worksheets("Sheet1").Range("AD7").Value <> Worksheets("Sheet1").Range("AC7").Value And Worksheets("Sheet1").Range("AB7").Value <> Worksheets("Sheet1").Range("AD7").Value
End Sub
but I'm receiving a Run-time error '1004': Application-defined or object-defined error
.
Is the above script the best way to solve the problem or is there a simpler solution (that is potentially generalizable to any number of columns)?
RandBetween(1,100000)
is less likely to have a dupe thanRandBetween(1,5)
, if you strictly need to prevent duplicates, then you'll need to implement some custom approach with VBA – David Zemens