我是Stack Overflow和VBA的新手,希望我不再重复之前提出的问题。
手头的问题是我希望VBA中的一个函数在满足条件时发回1,如果不满足则返回零,我无法使用下面的代码。
Sub Calculate(Total, X, Y, Z) 'doesn't work as expected
valid_vlaue = CInt(Validity(Total, X, Y, Z))
MsgBox valid_value
If valid_value = 1 Then
MsgBox "Yes, Proceed"
ElseIf valid_value = 0 Then
MsgBox "No, abort"
End If
End Sub
Function Validity(Total, X, Y, Z) As Integer
available_space = X * Y * Z
Total = CInt(Total)
available_space = CInt(available_space)
'My_check = VarType(Total)
'MsgBox My_check
If Total <= available_space Then
MsgBox "There is Room"
Validity = 1
Check = VarType(Validity)
MsgBox Check
Exit Function
ElseIf Total > available_space Then
MsgBox "There is not enough Room"
Validity = 0
Exit Function
End If
End Function
这不会按预期工作,也不会返回任何内容,并且始终会执行false语句。
然而,当我编写一个测试函数时,如下所示,一切都按预期工作。
Sub Test1() 'Works as expected
Check = Test22(1)
MsgBox Check
If Check = 1 Then
MsgBox "Proceed"
ElseIf Check <> 1 Then
MsgBox "Abort"
End If
End Sub
Function Test22(tmp) As Integer
If tmp = 1 Then
Test22 = 1
Exit Function
ElseIf tmp <> 1 Then
Test22 = 0
Exit Function
End If
End Function
有人可以向我解释我做错了什么。
提前致谢
答案 0 :(得分:0)
我没有用精美的牙齿梳理过这个但是
备注:强>
Option Explicit
置于顶部 - 强制声明并检查拼写以及是否传递预期类型,例如valid_value
或valid_vlaue
ByVal
关键字添加到签名中。目前隐含ByRef
。Private
或Public
。<强>代码:强>
Option Explicit
Public Sub test()
Calculate 12, 6, 3, 3
End Sub
Public Sub Calculate(ByVal Total As Long, ByVal X As Long, ByVal Y As Long, ByVal Z As Long) 'doesn't work as expected
Dim valid_value As Long
valid_value = Validity(Total, X, Y, Z)
MsgBox valid_value
If valid_value = 1 Then
MsgBox "Yes, Proceed"
ElseIf valid_value = 0 Then
MsgBox "No, abort"
End If
End Sub
Public Function Validity(ByVal Total As Long, ByVal X As Long, ByVal Y As Long, ByVal Z As Long) As Long
Dim available_space As Long
available_space = X * Y * Z
'My_check = VarType(Total)
'MsgBox My_check
Dim Check As Variant
If Total <= available_space Then
MsgBox "There is Room"
Validity = 1
Check = VarType(Validity)
MsgBox Check
Exit Function
ElseIf Total > available_space Then
MsgBox "There is not enough Room"
Validity = 0
Exit Function
End If
End Function
测试运行:
答案 1 :(得分:0)
因为有效性是给你一个go-no go结果然后你voukd使它成为布尔类型(True-False)
此外,您可以将代码(和错误!)减少到:
Sub Calculate(Total As Variant, X As Variant, Y As Variant, Z As Variant)
If CInt(Total) < CInt(X*Y*Z) Then ‘just make the check here!
MsgBox "Yes, Proceed"
Else
MsgBox "No, abort"
End If
End Sub
最后,由于有效性功能仅包含一行,您可以摆脱它:
{{1}}
答案 2 :(得分:0)
非常感谢您的帮助!拿起了很多好消息!
问题的核心原因是我拼写了#34; valid_value&#34;在顶部错了。尽管在发布问题之前我试图严格检查代码,但我还是错过了这个。
我会尽量利用我在这里得到的提示。
最好的问候
疥