2014-07-07 125 views
0

我正在試圖根據函數中給定的參數在不同的工作表上執行VLOOKUP。我已經玩了好幾個小時了,不知道爲什麼它不起作用。我儘可能多地減少了代碼,但無法有效地找到解決方案。我認爲這可能是我如何從VLOOKUP的其他工作表調用範圍的問題。代碼如下。請指教。如果我不清楚我要問什麼,我會提供反饋。謝謝Excel VBA - 自定義函數; #VALUE錯誤;在不同的工作表上的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 
+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 
+0

我現在能夠發現錯誤,但我仍然無法單獨進行Match功能。 GraphDataA = WorksheetFunction.Match(dat,Worksheets(「DayTot」)。Range(「I3:EK3」),0) 該函數是否應該基於DayTot!I3:EK3數組中的假設工作? – TheBriStar

+0

在代碼中將'MATCH'和'VLOOKUP'拆分成不同的行,即將中間匹配值存儲在一個變量中,然後在VLOOKUP中使用。通過使用兩個斷點找出哪個步驟正在生成錯誤,然後 – hnk

+0

我分離了VLOOKUP並匹配並確定了匹配中的錯誤。這是一個範圍問題。謝謝。 – TheBriStar

-1

你似乎沒有從你的函數返回任何值。嘗試添加As Variant到第一行的末尾,像這樣:如果沒有匹配

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

但OP從函數返回值。在VBA中,用函數名稱替換'return'。 –

+0

@mehow儘管如Gareth指出的那樣,他不需要指定返回類型嗎? – rex

+1

@ ArmenSafieh-Garabedian默認返回類型是變體 –