This function returns a random value from a range, but only if it meets the criteria in another column.
Item color? animal?
red yes no
cow no yes
dog no yes
blue yes no
ferrari no no
RetrunIf(A2:A6,"yes",2) = red or blue
RetrunIf(A2:A6,"yes",3) = cow or dog
RetrunIf(A2:A6,"yes",2,3) = red or blue or cow or dog
It works great... unless I reference a range on another sheet.
RetrunIf(otherSheet!A2:A6,"yes",2) = "blank"
Is there a problem with using the Range data type for ranges on other sheets?
Here she is: (Disclosure: I am not the author. Was purpose built for me by a coworker, and I only have a basic understanding of how it works.)
Function RandBetweenVBA(Low As Integer, High As Integer)
RandBetweenVBA = Int((High - Low + 1) * Rnd + Low)
End Function
Function ReturnIf(Source As Range, Criteria As Variant, ConditionColumn1 As Integer, Optional ConditionColumn2 As Variant)
'Get the base column and row of the source range.
Dim BaseColumn As Integer: BaseColumn = Source(1, 1).Column
Dim BaseRow As Integer: BaseRow = Source(1, 1).Row
'Get all rows that match the criteria.
Dim MatchingRows() As Integer: ReDim MatchingRows(0 To 0) As Integer
Dim I As Integer
For I = 0 To Source.Count - 1
If Cells(BaseRow + I, ConditionColumn1).Value = Criteria Or ((Not IsMissing(ConditionColumn2)) And Cells(BaseRow + I, ConditionColumn2).Value = Criteria) Then
ArrayPush Arr:=MatchingRows, Value:=BaseRow + I
End If
Next
If UBound(MatchingRows) = 0 Then
ReturnIf = ""
Else
ReturnIf = Cells(ArrayGetRandomElement(MatchingRows), BaseColumn).Value
End If
End Function
Sub ArrayPush(ByRef Arr() As Integer, Value As Integer)
ReDim Preserve Arr(0 To UBound(Arr) + 1) As Integer
Arr(UBound(Arr)) = Value
End Sub
Function ArrayGetRandomElement(Arr() As Integer)
Dim index As Integer: index = RandBetweenVBA(1, UBound(Arr))
ArrayGetRandomElement = Arr(index)
End Function
Bookmarks