Excel VBA - 自定义功能; #VALUE错误; VLOOKUP在不同的工作表上

时间:2014-07-07 12:32:00

标签: excel vba excel-vba vlookup worksheet-function

我试图根据函数中给定的参数在不同的工作表上进行VLOOKUP。我玩了好几个小时,无法弄清楚它为什么不起作用。我尽可能地减少了代码以进行测试,但无法有效地找到解决方案。我想这可能是我如何从VLOOKUP的另一个工作表调用范围的问题。代码如下。请指教。如果我不清楚我要问的是什么,我会提供反馈。谢谢

Function GraphDataA(cR As String, time As String, aClient As String, tps As String, dat As String)

Dim client As Boolean
Dim day As Boolean
Dim tot As Boolean

Dim dayTotData As Range
Dim dayTotDatas As Worksheet


Set dayTotDatas = ActiveWorkbook.Sheets("DayTot")
Set dayTotData = dayTotDatas.Range("A3:AI168")

client = False
day = False
tot = False

If date = "" Then
    GraphDataA = ""
End If

If aClient = "" Then
    GraphDataA = ""
End If

If cR = "Client" Then
    client = True
End If

If time = "Day" Then
    day = True
End If

If tps = "Total" Then
    tot = True
End If

If client = True Then
    If day = True Then
        If tot = True Then
            GraphDataA = WorksheetFunction.VLookup(aClient, dayTotData, WorksheetFunction.Match(dat, dayDate, 0) + 8, _
        False)
        End If
    End If
End If
End Function

2 个答案:

答案 0 :(得分:1)

如果没有匹配,

VLOOKUP()将抛出错误。因此,您需要在函数中添加错误捕获代码。

您需要将功能修改为

Function MyFunction() as Something
    On Error Goto ErrorHandler
    ' Your existing code goes here
    Exit Function
ErrorHandler:
    MyFunction = -1 ' Or something which indicates that the value isn't found
End Function

答案 1 :(得分:-1)

您似乎没有从您的功能中返回任何值。尝试将As Variant添加到第一行的末尾,如下所示:

Function GraphDataA(cR As String, time As String, aClient As String, tps As String, dat As String) As Variant