The code below works in randomly selecting any entry in Column "Exercise" and outputting it to Cell X8, but it is supposed to find rows where it finds a match for the text in cell V8, and then randomly choose one of these rows and then output the data in the corresponding cell of column "Exercise". Can anyone help?
VBA Code:
Private Sub CommandButton4_Click()
Dim rngType As Range
Dim rngExercise As Range
Dim cell As Range
Dim rowMatch As Long
Dim rowCount As Long
' Set the named ranges for "Type" and "Exercise"
Set rngType = ThisWorkbook.Names("Type").RefersToRange
Set rngExercise = ThisWorkbook.Names("Exercise").RefersToRange
' Get the number of rows in the "Exercises" sheet
rowCount = Worksheets("Exercises").UsedRange.Rows.count
' Find the rows where there is a match for V8 in named range "Type"
For Each cell In rngType
If cell.Value = Range("V8").Value Then
' Randomly choose a row that meets the specified criteria
rowMatch = Int((rowCount - 1) * Rnd + 1) + 1 ' Add 1 to skip the header row
' Output the corresponding entry from named range "Exercise" in cell X8
Range("X8").Value = Worksheets("Exercises").Range("A" & rowMatch).Offset(0, rngExercise.Column - 1).Value
Exit Sub ' Exit the loop once a matching row is found
End If
Next cell
' If no matching row is found, output an error message
MsgBox "No matching row found."
End Sub