0

不幸的是,有时当 if 语句更复杂时,行为很奇怪,这里是该行的副本,当这样使用时,它不能按预期工作

If someFunction(arg1, arg2, CreatedFromClass(arg3, arg4, arg5)) Then GoTo err1

someFunction(...)本身的返回类型为 long,但在这种情况下,绝对总是被评估为正数,即使return 之前的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

但是 when 被分割成段,并手动分配给变量,然后按预期工作

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

当然,所有这些都将被评估为 True 有效并打印结果!

4

1 回答 1

0

是的,我找到了我的问题的答案,在 Catia 中,我有 VBA 版本 7.1.1033,它不能按预期工作,而同一段代码在 Excel 中工作,它使用较新的 VBA 版本,7.1.1049 ...

所以答案是,VBA 在那个版本中有错误..

于 2016-03-29T08:15:27.197 回答