2012-06-01 95 views
0

我有一个函数可以查找某个范围内的当前日期并返回找到它的单元格。我试图使用该单元格的位置来计算子例程内的偏移量。但是,当我运行宏时,我得到objected required作为错误。功能和子程序被如图所示:使用函数返回值时出现“object 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

回答

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

你将需要检查的东西寻找行属性之前返回。没有东西没有排。一行是一个数字,而不是一个对象。

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 
+0

如果我从'wkday_row_offset'行删除了'Set'关键字,我得到以下错误:'Object variable or with block variable not set'任何其他想法? –

+0

根据您的更新,我将如何检查是否返回了一些内容?由于我几分钟前测试了这个函数,它*会*返回一个值,因为工作表中存在搜索字符串“6/1/2012”。因此,函数(在这种情况下)不应该返回一个值吗? –

+0

您需要设置搜索功能,'set findCurrentDate = search'。你说这是一个片段,并被问到一个错误。 – Fionnuala

相关问题