【问题标题】:Excel VBA - Custom Function; #VALUE error; VLOOKUP on different worksheetExcel VBA - 自定义函数; #VALUE 错误;不同工作表上的 VLOOKUP
【发布时间】:2014-08-27 22:36:48
【问题描述】:

我正在尝试根据函数中的给定参数在不同的工作表上执行 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

【问题讨论】:

    标签: vba excel vlookup worksheet-function


    【解决方案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
    

    【讨论】:

    • 我现在能够捕捉到错误,但我仍然无法单独执行匹配功能。 GraphDataA = WorksheetFunction.Match(dat, Worksheets("DayTot").Range("I3:EK3"), 0) 该函数是否应该基于 dat 在 DayTot!I3:EK3 数组中的假设工作?
    • 在代码中将MATCHVLOOKUP 拆分为单独的行,即将中间匹配值存储在一个变量中,然后在VLOOKUP 中使用它。通过在两者上使用断点找出哪个步骤产生错误,然后
    • 我拆分了 VLOOKUP 和 Match 并发现了 Match 中的错误。这是范围的问题。谢谢。
    【解决方案2】:

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

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

    【讨论】:

    • 但 OP 正在从函数返回值。在 VBA 中,您将 return 替换为函数名称。
    • @mehow 他不必像 Gareth 指出的那样指定返回类型吗?
    • @ArmenSafieh-Garabedian 默认返回类型是 Variant
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多