VBA UDF返回数组

我有以下的UDF,需要循环表格中的所有数据称为类,并返回学生的姓名和类名称(列A和B),如果学生姓名显示在名单上的时间表名单这个列表在单元格BM3到BM21中),并且类别在UDF中input的date和时间发生。 目前它返回一个#Value错误。 我做错了什么?

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 

如果你想返回一个数组,你可以定义这个函数为Variant,但是最好把你的函数头改为这个(使得更容易直接看到函数的返回types):

 Function TTDisplay(Day As String, Time As Variant) As String() 

在最后一行( TTDisplay = Result(1) ),你只返回一个值,所以改变它返回整个数组: TTDisplay = Result

TTDisplay = Result(1)将UDF的值设置为数组中的第一个元素。 TTDisplay = Result将返回完整的数组。
您还必须使用Ctrl + Shift + Enter {=TTDisplay($A2,$B2)}将公式input为数组公式。

我修改了你的代码,使数组dynamic。

 Function TTDisplay(Day As String, Time As Variant) As Variant Dim Result() 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 = 0 ReDim Result(x) 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 ReDim Preserve Result(x) 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 ReDim Preserve Result(x) 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 End Function