简体   繁体   中英

Excel VBA - Custom Function; #VALUE error; VLOOKUP on different worksheet

I am attempting to do a VLOOKUP on a different worksheet based on given parameters in the function. I've played around with it for several hours and can not figure out why it is not working. I cut down the code as much as I could to test, but am unable to effectively find a solution. I think it might be an issue of how I am calling the range from the other worksheet for the VLOOKUP. Code is below. Please advice. If I'm unclear about what I'm asking just ask and I will provide feedback. Thank you

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

VLOOKUP() will throw an error if nothing matches. So you need to add error catching code to your function.

You need to modify the function as

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

You don't appear to be returning any value from your function. Try adding As Variant to the end of the first line like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM