2015-04-17 28 views
-2

我正在嘗試創建一個函數,它將計算產品的總數量爲「pn001」,減去另一個表中的總和,答案應顯示在調用該函數的表中#VALUE!在工作表上調用UDF函數時出錯

Function salio() As Long 

    Dim Sumact As Range 
    Dim Sumact1 As Range 
    Dim Remain As Long 
    Dim RR As Long 
    Dim R As Long 

    Set Sumact = Sheets(1).Range("A1") 
    Set Sumact1 = Sheets("SALES").Range("A1") 
    Sheets("STOCK-OUT").Select 
    Sumact = Application.SumIf(Range("C3:C5"), "pn001", Range("E3:E5")) 
    RR = CLng(Sumact) 
    Sheets("SALES").Select 
    Sumact1 = Application.SumIf(Range("D2:D5"), "pn001", Range("F2:F5")) 
    Remain = CLng(Sumact1) 
    R = RR - Remain 
    salio = R 
End Function 

我得到的只是#VALUE!當我嘗試在工作表上使用此錯誤時出錯。

+0

**你的問題是什麼?**你已經有了一些代碼。它工作嗎? –

+0

你真的需要一個UDF來做到這一點嗎?你的代碼只是模仿Excel的本地公式已經可以做的事情。當然你可以在沒有任何VBA的情況下完成這個任務 –

回答

0

如果你在模塊代碼表中,而不是工作表代碼表,那麼我懷疑你的問題與在函數中使用.Select有關。 Select方法可以在宏Subs中使用,但不能在工作表中使用的函數中切換工作表。你也不能把值到了一個UDF的功能駐留在任何其他細胞。

Function salio() As Long 
    'Dim Sumact As Range you cannot set these to a range to receive a sumif 
    'Dim Sumact1 As Range you cannot set these to a range to receive a sumif 
    Dim Sumact As Long 
    Dim Sumact1 As Long 
    Dim Remain As Long 
    Dim RR As Long 
    Dim R As Long 

    'Set Sumact = Sheets(1).Range("A1") you cannot set these to a range to receive a sumif 
    'Set Sumact1 = Sheets("SALES").Range("A1") you cannot set these to a range to receive a sumif 
    With Sheets("STOCK-OUT") 'do not .Select - Use With ... End With to reference another worksheet 
     Sumact = Application.SumIf(.Range("C3:C5"), "pn001", .Range("E3:E5")) 
    End With 
    RR = CLng(Sumact) 
    With Sheets("SALES") 'do not .Select - Use With ... End With to reference another worksheet 
     Sumact1 = Application.SumIf(.Range("D2:D5"), "pn001", .Range("F2:F5")) 
    End With 
    Remain = CLng(Sumact1) 
    R = RR - Remain 
    salio = R 
End Function 

我留下了一些死代碼在那裏還有一些意見。您還需要查看How to avoid using Select in Excel VBA macros

+0

謝謝很多人je,,你的答案是有效的!!!!!!!! – CODER