3

我有一个简短的问题。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 的数量会扼杀这种速度优势?

4

2 回答 2

9

单班机正在检查所有条件,无论是否有任何条件已经失败。

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 块并且不尝试评估所有其他条件。

这是编程中的一种短路形式。

于 2014-12-08T10:21:09.420 回答
3

就优化而言,嵌套 If 将是更好的选择。如果条件失败,嵌套 If 将忽略所有其他后续内容,但是如果使用 AND(或)OR 的一行将不会被优化,因为在达到判决之前执行每个单个条件。此外,嵌套 If 的代码可读性和可维护性要好得多(前提是它们正确缩进)。

所以嵌套如果在任何一天为我使用多个条件!

于 2014-12-08T10:19:48.030 回答