vba - 嵌套的 "if"和使用 "if x and y and z and .."在速度方面有区别吗?

标签 vba ms-access if-statement flow-control

这个问题在这里已经有了答案:





Does the VBA "And" operator evaluate the second argument when the first is false?

(7 个回答)


6年前关闭。




我有一个简短的问题。 VBA 之间有什么区别吗

if x1 and x2 and x3 and ... and x10 then
    foo
end if


if x1 then
  if x2 then
    if x3 then
      ...
      foo
    end if
  end if
end if

关于速度?

进一步来说:
我有 10 列数据,需要逐行比较数据库中的重复数据(像 SELECT DISTINCT 这样的东西在这种情况下不起作用)。

我可以想象,使用
x1 = recordset.fields("Field1").value
if x1 then
  x2 = recordset.fields("Field2").value
  if x2 then
    x3 = recordset.fields("Field3").value
    if x3 then
      ...
      foo
    end if
  end if
end if

将比
x1 = recordset.fields("Field1").value
x2 = recordset.fields("Field2").value
...
if x1 and x2 and x3 and ... and x10 then
    foo
end if

因为我不必从记录集中读取所有数据。或者 ifs 的数量会扼杀这个关于速度的优势吗?

最佳答案

one-liner 正在检查所有条件,忽略它们中的任何一个是否已经失败。

Sub Main()
    If Check And Check And Check Then
    End If
End Sub

Function Check() As Boolean
    Debug.Print "checked"
    Check = False
End Function

嵌套的 if 是更好的选择,因为只要一个条件失败,代码执行就会立即跳转到任一:else/end if 块,而不是尝试评估所有其他条件。

这是 short-circuiting in programming 的一种形式.
  • VBA Short-Circuit `And` Alternatives
  • Does the VBA "And" operator evaluate the second argument when the first is false?
  • 关于vba - 嵌套的 "if"和使用 "if x and y and z and .."在速度方面有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27355645/

    相关文章:

    vba - 在 VB6/VBA 项目引用中,Array()、LBound() 和 UBound() 来自哪里......?

    vba - 如何使用 vba 读取粘贴在 Outlook 邮件正文中的表格?

    algorithm - O(n) 中的 MS-Access 数据库搜索算法?

    php - 如何使用 PHP 将 mdb 文件转换为 mysql 文件或 mysql 命令?

    python - 如何使用 python ast 模块来分析 if 语句

    C# 斐波那契数列复制

    vba - Excel VBA 脚本在 URL 列表中查找 404 错误?

    vba - 通过MS Access 2003 [VBA]中的代码动态创建查询

    python - 永久更改 Microsoft Access 数据库的密码(通过 Python)

    r - 如何在 R 中使用 ifelse 条件从向量中删除