我正在尝试创建一个函数,用于计算数字" pn001"的产品总数量。减去另一张表中的总和,答案应显示在名为
的函数表中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)
如果您在模块代码表中有此代码而不是工作表代码表,那么我怀疑您的问题与在函数中使用.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。