2014-07-11 115 views
1

我已经足够长练成这样VBA函数在Excel中返回值

IF(ISNUMBER(E6),IF(E6<standard_hour,0,IF(((E6-standard_hour)*24*60)>90,2,CEILING(((E6-standard_hour)*24*60)/30*0.5,0.5))),VLOOKUP(E6,Refer,2,FALSE)) 

公式,因为我在电子表格中使用这个公式了很多,我决定做一个自定义的功能吧。这是函数

Function morning_check(start_hour) 
    Dim sheet As Worksheet 
    Set sheet = ActiveWorkbook.Sheets("Setup") 

    If WorksheetFunction.IsNumber(start_hour) Then 
     If start_hour < sheet.Range("E1").Value Then 
      morning_check = 0 
     Else 
      If ((start_hour - sheet.Range("E1").Value) * 24 * 60 > 90) Then 
       morning_check = 2 
      Else 
       morning_check = Application.WorksheetFunction.Ceiling(((start_hour - sheet.Range("E1")) * 24 * 60)/30 * 0.5, 0.5) 
      End If 
     End If 
    Else 
     morning_check = Application.WorksheetFunction.VLookup(start_hour, sheet.Range("Refer"), 2, False) 
    End If 

End Function 

此函数的输入可以是字符串(例如:“TS”)或时间(例如:07:00)

使用字符串作为输入时,该功能正常工作,但当我使用时间只是抛出#Value!

+0

哪一行是错误的来源?如果您选择调试,Excel应该突出显示它。 –

+0

它的亮点第一行​​ – l1th1um

回答

1

你的错误是由以下行来:

Set standard_hour = TimeValue(sheet.Cells("E1")) 
Set user_hour = TimeValue(start_hour) 

在VBA Set用于创建对象,而你只是想设置一个变量。这就是为什么你会收到“Object Required”错误。

只要放下Set这个词,你应该可以继续进行调试。作为一个调查问题(如果你的Excel副本的行为与我一样),Excel突出显示了黄色的第一行(这没有帮助),但它也自动选择了文本standard_hour(它标识了问题)。

+0

嗨,我编辑我的代码,现在它不会再次抛出错误,但它仍然不工作的非字符串(中频的第一分支) – l1th1um

+0

只需忽略,现在一切工作正常,在最后一步我忘了格式化我的手机:D。无论如何,谢谢你的解释。这是我第一次使用VBA – l1th1um