使用函数返回值时出现“对象是否需要”错误?

时间:2012-06-01 18:41:58

标签: vba

我有一个函数可以在一个范围内找到当前日期并返回找到它的单元格。我正在尝试使用该单元格的位置来计算子程序中的偏移量。但是,当我运行宏时,我得到objected required错误。函数和子程序如下所示:

Function findCurrentDate() As Range
    Dim needle As Date
    Dim rng As Range
    needle = CLng(Date)
    Dim haystack As Range
    Dim search As Range
    Set haystack = Range("B3:B86")
    Set search = haystack.Find(needle, After:=haystack(1), _
                           LookIn:=xlValues, Lookat:=xlWhole, _
                           SearchOrder:=xlNext, MatchByte:=True)
End Function

Sub showFutureWeeklyHours()
    Dim wkday_row_offset As Integer
    Dim search As Range
    Set search = findCurrentDate()
    Set wkday_row_offset = search.Row
...
End Sub

这不是完整的子程序,但它足以重现错误。日期列表存储在单元格B3:B86

1 个答案:

答案 0 :(得分:2)

这个wkday_row_offset是一个数字,而不是一个对象,所以不要使用Set。

"This method returns Nothing if no match is found. The Find method does not affect the selection or the active cell."

http://msdn.microsoft.com/en-us/library/ff839746.aspx

在查找row属性之前,您需要检查是否返回了某些内容。什么都没有。行是数字,而不是对象。

Function findCurrentDate() As Range
    Dim needle As Date
    Dim rng As Range
    needle = CLng(Date)
    Dim haystack As Range
    Dim search As Range
    Set haystack = Range("B3:B86")
    Set search = haystack.Find(needle, After:=haystack(1), _
                           LookIn:=xlValues, Lookat:=xlWhole, _
                           SearchOrder:=xlNext, MatchByte:=True)
    Set findCurrentDate = search
End Function

Sub showFutureWeeklyHours()
    Dim wkday_row_offset As Integer
    Dim search As Range
    Set search = findCurrentDate()

    wkday_row_offset = search.row
''...
End Sub