不幸的是,有时当if语句更复杂时,行为很奇怪,这里是一行的副本,当这样使用时,它不能按预期工作
If someFunction(arg1, arg2, CreatedFromClass(arg3, arg4, arg5)) Then GoTo err1
someFunction(...)本身的返回类型为long,但在这种情况下绝对总是被评估为正数,即使返回前的 someFunction 包含0作为返回值。
因此,它可以包装为以下任何一种,结果将始终为真
If someFunction() = True Then
If someFunction() = False Then
If someFunction() = 0 Then
If someFunction() = 1 Then
If someFunction() <> 0 Then
If someFunction() <> 1 Then
If Not someFunction() = 0 Then
If Not someFunction() = 1 Then
If (someFunction() = 0) = False Then
If (someFunction() = 0) = True Then
If CBool(someFunction() = 0) = True Then
If CBool(someFunction() = 1) = True Then
但是当分割成段并手动分配给变量时,则按预期工作
Dim rVal As Long
rVal = someFunction(arg1, arg2, CreatedFromClass(arg3, arg4, arg5))
If rVal Then GoTo err1
问题当然是为什么行为不一样?有人经历过类似的事吗?
此外,几个小时后,我能够分离出有问题的代码!
类:cls.cls
Option Explicit
Private mCol As Collection
Private Sub Class_Initialize()
Set mCol = New Collection
End Sub
Private Sub Class_Terminate()
Set mCol = Nothing
End Sub
Public Sub Add(iItem)
mCol.Add iItem
End Sub
Public Function DoCopy() As cls
Set DoCopy = New cls
Dim i As Long
For i = 1 To mCol.Count
DoCopy.Add mCol(i)
Next
End Function
和测试模块
Option Explicit
Public Function CreateCls(ParamArray params()) As cls
Set CreateCls = New cls
If UBound(params) < 0 Then Exit Function
Dim i As Long
For i = LBound(params) To UBound(params)
CreateCls.Add params(i)
Next
End Function
Private Function doTest(iCls As cls) As Long
doTest = 0
End Function
Private Sub CATStart()
Dim x As cls
Set x = CreateCls("param1", "param2", "param3", "param4")
If doTest(x.DoCopy) = 0 Then Debug.Print "long_0"
If doTest(x.DoCopy) = 1 Then Debug.Print "long_1"
If CBool(doTest(x.DoCopy)) = True Then Debug.Print "bool_True"
If CBool(doTest(x.DoCopy)) = False Then Debug.Print "bool_False"
Set x = Nothing
End Sub
当然,所有这些都将被评估为真有效并打印结果!
答案 0 :(得分:0)
是的,我在我的问题上找到了答案,在Catia,我有VBA版本7.1.1033,它没有按预期工作,而同一段代码在Excel中工作,它使用更新的VBA版本,7.1.1049 ......
答案是,VBA在该版本中有错误。