I'm trying to random between an excel range and get a non-duplicated result.
I get a cell value when I type Msgbox Range("C2").
However, when I use MsgBox Range("F" & WorksheetFunction.RandBetween(1, UBound(ElementHeader))), it tells me 'type-mismatch'.
Any idea why? And how do I actually store it into a String array in VBA?
My code looks like this:
Sub Testy()
Dim ElementHeader
ElementHeader = Range("F1:F" & Range("F" & Rows.Count).End(xlUp).Row)
MsgBox Range("F" & WorksheetFunction.RandBetween(1, UBound(ElementHeader)))
End Sub
This is just part of the code, but I'm looking to store it into a array so I can check each of them to see if there are any duplicates.
Sub GenerateDescription()
Dim Element
Dim AddOn
Dim MainRange
' Declare Sentences
' Addon Range is in Column F
AddOn = Range("G1:G" & Range("G" & Rows.Count).End(xlUp).Row)
' Main Range is in Column D
Set MainRange = Range("E1:E" & Range("E" & Rows.Count).End(xlUp).Row)
For Each Element In MainRange
Element.Offset(, 4).Value = Element & " " & Range("G" & WorksheetFunction.RandBetween(1, UBound(AddOn))) & " " & Range("G" & WorksheetFunction.RandBetween(1, UBound(AddOn))) & " " & Range("G" & WorksheetFunction.RandBetween(1, UBound(AddOn))) & " " & Range("G" & WorksheetFunction.RandBetween(1, UBound(AddOn))) & " " & Range("G" & WorksheetFunction.RandBetween(1, UBound(AddOn)))
Next Element
End Sub
As you can see, this repeated G Range is the part I'm trying to solve.
I want the Column G sentences to appear only once per For Each method. Meaning, I want each element to contain 5 unique sentences from Column G.
Let's say I have 10 sentences, and for each loop, I want to get 5 unique sentences, which for example is: G1, G4, G2, G9, G10. There should never be a repeat of the same cell, meaning if the function generates G1, G2, G5, G3, G1, I want to replace the duplicate G1 with another random cell number from Column G.
Msgbox UBound(ElementHeader)will tell you what the problem is.type-mismatch.Range("F2:F" & Range("F" & Rows.Count).End(xlUp).Row)this counts the row...