为什么我创建的函数返回错误?

时间:2018-07-17 15:28:57

标签: excel-vba

我创建了一个具有4个参数的函数:SearchDate,StartDate,EndDate,Events。我希望函数起作用的方式是,如果SearchDate对于某个开始日期为> =,对于某个结束日期为= <,则该函数提取事件名称。例如,如果搜索是6月17日,开始/结束日期是6月15日/ 6月18日,则它将取消该事件。

但是代码似乎不起作用;当我尝试使用它给我一个价值错误。我在下面发布了该函数所基于的代码和表格。

Function Calendar_Events(SearchDate As Date, StartColumn As Range, EndColumn As Range, EventsColumn As Range)

Dim x As Long
Dim output As Range
For x = 1 To StartColumn.Cells.CountLarge
    If Int(StartColumn.Cells(x)) <= SearchDate And Int(EndColumn.Cells(x)) >= SearchDate Then
       'in place for the case of more events then rows 
       If y >= 3 Then
           output = output & "........"
           Exit For
       End If
       output = output & Left(EventsColumn.Cells(x), 20) & vbNewLine
       y = y + 1
    End If
Next x

End Function

表格:

Start Date  End Date    Event

1/12/2018   1/19/2018   Software Sale
1/31/2018   1/31/2018   Dinner Party
2/1/2018    2/1/2018    Baby Shower
2/12/2018   2/16/2018   Team Retreat
2/15/2018   2/16/2018   Bank Meetings
2/15/2018   2/15/2018   Lunch Date
2/15/2018   2/15/2018   Dinner Date
3/26/2018   3/29/2018   Vacation
3/28/2018   3/29/2018   Swimming
3/28/2018   3/28/2018   Mountain Biking
3/29/2018   3/29/2018   Put away clothes
3/29/2018   4/4/2018    Cottage 
4/2/2018    4/2/2018    Family Photo
4/2/2018    4/4/2018    Software Sale
4/2/2018    4/6/2018    Hire Nanny
4/6/2018    4/6/2018    Day Off

1 个答案:

答案 0 :(得分:1)

1。。要从功能返回值,必须将功能名称设置为要返回的值。

因此,在代码末尾,您需要:

Calendar_Events = output

因此它知道返回您一直在构建的output变量。

2。。此外,您的output变量应为String。您不是在这里收集Ranges,而是在符合条件的单元格内部收集值,所以:

Dim Output As String

3。。此外,也无需将包含日期的单元格值转换为整数。您正在将日期与日期进行比较,这很不错,无需进行转换。所以:

If StartColumn.Cells(x).Value <= SearchDate And EndColumn.Cells(x).Value >= SearchDate Then

我还在.value引用的末尾添加了Cell()。它将默认使用单元格的.value属性,但是我非常喜欢显式编码,而不仅仅是希望编译器知道您的意思是什么。

4。最后,(可选)您应该在函数定义中声明该函数的返回类型。所以:

Function Calendar_Events(SearchDate As Date, StartColumn As Range, EndColumn As Range, EventsColumn As Range) As String

所有这些在一起:

Function Calendar_Events(SearchDate As Date, StartColumn As Range, EndColumn As Range, EventsColumn As Range) As String

    Dim x As Long
    Dim output As String
    For x = 1 To StartColumn.Cells.CountLarge
        Debug.Print StartColumn.Cells(x).Value, EndColumn.Cells(x).Value
        If StartColumn.Cells(x).Value <= SearchDate And EndColumn.Cells(x).Value >= SearchDate Then
           'in place for the case of more events then rows
           If y >= 3 Then
               output = output & "........"
               Exit For
           End If
           output = output & Left(EventsColumn.Cells(x), 20) & vbNewLine
           y = y + 1
        End If
    Next x
    Calendar_Events = output
End Function