0

我有一个函数可以在一个范围内查找当前日期并返回找到它的单元格。我正在尝试使用该单元格的位置来计算子程序中的偏移量。但是,当我运行宏时,我得到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

4

1 回答 1

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
于 2012-06-01T18:47:15.347 回答