I have the following UDF which needs to loop through all the data on the sheet called Classes and return the names of the students and the class names (columns A and B) if the students name is displayed in a list on the sheet called Timetable (this list is in cells BM3 to BM21) and the class takes place on the day and time entered in the UDF. Currently it returns a #Value error. What have I done wrong?
Function TTDisplay(Day As String, Time As Variant) As Variant
Dim Result(1 To 12) As String
Dim Students As String
Dim cell As Integer
Dim LastRow As Long
Dim Classes As Worksheet
Dim Timetable As Worksheet
Dim x As Integer
Dim TimeSpan As Integer
Dim TTTime As Integer
Classes = Sheets("Classes")
Timetable = Sheets("Timetable")
LastRow = Classes.Cells(Classes.Rows.count, "A").End(xlUp).Row
TTTime = TMins(Time)
For cell = 3 To 21
Students = Students & Timetable.Cells(cell, 65).value & "!"
Next cell
x = 1
For cell = 2 To LastRow
If InStr(Students, Classes.Cells(cell, 2)) Then
If Day = Classes.Cells(cell, 9) Then
If Time = Classes.Cells(cell, 12) Then
Result(x) = Classes.Cells(cell, 2) & Chr(10) & Classes.Cells(cell, 1)
x = x + 1
Else
TimeSpan = TMins(Classes.Cells(cell, 12)) + 30
Do While TimeSpan < TMins(Classes.Cells(cell, 11))
If TimeSpan = TTTime Then
Result(x) = Classes.Cells(cell, 2) & Chr(10) & Classes.Cells(cell, 1)
x = x + 1
GoTo MoveOn
Else
TimeSpan = TimeSpan + 30
End If
Loop
MoveOn:
End If
End If
End If
Next cell
TTDisplay = Result(1)
End Function
Resultis 1 to 12, are you sure there are no more than 12 entries? Directly afterFor cell = 2 To LastRowput inIf x = 13 Then Exit Forand check again... or better, run the code line by line...