自定义 VBA 函数引发意外输出 [重复]
Posted
技术标签:
【中文标题】自定义 VBA 函数引发意外输出 [重复]【英文标题】:Custom VBA Function throws unexpected output [duplicate] 【发布时间】:2021-09-16 09:47:09 【问题描述】:我正在尝试编写一个自定义公式,向我展示低货架可用性(又名 OSA)的原因。我已经植入了所有嵌套的 if 语句,并希望从 debug.print 语句中看到文本,但在所有情况下,我都收到 0 作为答案。我做错了什么?
代码低于
*Option Explicit*
Function Octopus (PNZ As Double, OSA As Double, SL As Double, Current_Stock As Integer, SO_Month As Integer, Client_SI_Forecast As Integer, SO_FCST As Integer, SO_Fact As Integer, Availability_Report As Double, Client_FA As Double, OTIF As Double)
'Make formula update like an excel formula
Application.Volatile True
If Current_Stock / PNZ >= 1 Then
'OSA Check
If OSA > 0.9 Then
' Checking Sell Out dynamics
If SO_Fact / (1 - PNZ) > 1.2 * Client_SI_Forecast Then
Debug.Print " Under Forecast. Increase PNZ"
Else
Debug.Print "No Problems Discovered"
End If
Else
' Checking if SO is zero
If SO_Fact > 0 Then
' Comparing Stock to its monthly average
If Current_Stock < SO_Month Then
Debug.Print "No Spare space on shelf, possible virtual stock"
Else
Debug.Print "No Spare space on shelf, possible delay on layout"
End If
Else
Debug.Print "Virtual Stock"
End If
End If
Else
If OSA > 0.9 Then
If Availability_Report > 0.9 Then
Debug.Print "No Problems Discovered"
Else
Debug.Print "Incorrect PNZ tuning"
End If
Else
If SL > 0.9 Then
If PNZ > SO_Fact * 2 / 7 Then
If Client_FA > 0.8 Then
Debug.Print "Double-Check PNZ"
Else
Debug.Print "Adress FA Issue to Client Forecasting Team"
End If
Else
Debug.Print " Update PNZ value"
End If
Else
If OTIF > 0.8 Then
Debug.Print " We Didn't have product"
Else
Debug.Print " Issues with our logisttics "
End If
End If
End If
End If
End Function
【问题讨论】:
请添加一组常用输入参数,不知道任何值很难通过代码。 Y你在哪里设置函数中Octopus
的值?
从 sub 调用你的函数,这样你就可以单步执行它
1. 在Application.Volatile True
行上方,输入Dim Ret as String
2。 将Debug.Print
替换为Ret =
3 . 最后在End Function
之前,输入Octopus = Ret
【参考方案1】:
您似乎没有在任何地方设置返回值。这是一个非常基本的 VBA 函数:
Function TwicePlusOne(Input AS Long) As Long
Dim TempValue As Long
TempValue = Input *2
TwicePlusOne= TempValue + 1 'This sets the Output value
End Function
由于您的Octopus
函数没有Octopus = <VALUE>
行,因此它将始终返回默认值0
是可以使用ByRef
通过变量传递输出,但我不是特别喜欢这样做。这是一个例子:
Function TwicePlusOne_ByRef(ByVal Input As Long, ByRef Output AS Long) As Boolean
TwicePlusOne_ByRef = False
On Error GoTo AbortFunction 'In case something goes wrong
Dim TempValue As Long
TempValue = Input *2
Output = TempValue + 1 'This sets the Output value
TwicePlusOne_ByRef = True 'Tell us that the function has worked
AbortFunction:
On Error GoTo -1 'Clear the Error Handler
End Function
Sub UseTheFunction()
Sub StartValue AS Long, EndValue AS Long
StartValue = 4
If TwicePlusOne_ByRef(StartValue, EndValue) Then
MsgBox "Twice " & StartValue & " plus 1 is " & EndValue
Else
MsgBox "There was an error in the function"
End If
End Sub
【讨论】:
你是对的!现在一切正常,赞!以上是关于自定义 VBA 函数引发意外输出 [重复]的主要内容,如果未能解决你的问题,请参考以下文章