【问题标题】:VBA Function Avoiding If Statements避免 If 语句的 VBA 函数
【发布时间】:2013-06-17 20:56:20
【问题描述】:

我正在构建一个非常复杂的 VBA 工作簿,而运行大部分代码的问题之一是性能。我有一个内置函数,或多或少,如下

Public Function zzz (xxx as String) as String
if xxx = "apple" then zzz = "orange"
if xxx = "appple2" then zzz = "orange2"
if xxx = "apple3" then zzz = "apple3"

等等。 (但用大约 30 个字符串代替)。我多次调用这个函数。有没有更好的方法来做到这一点?

【问题讨论】:

  • 你最好使用vlookup()
  • 你至少可以使用if else
  • 这是查找值和结果值的真实示例吗?

标签: vba if-statement


【解决方案1】:

几乎没有。对于 30 个字符串,这应该不会太慢。

性能问题可能在其他地方,尤其是在您直接与工作簿交互的地方。在随机尝试更新代码之前尝试测量各种过程的时间。

行数多并不意味着性能低下。并非每一行都需要相同的时间来执行。

【讨论】:

    【解决方案2】:

    您可以使用数组和WorksheetFunction.Match 的组合来创建您的函数。这将是这样的:

    Public Function zzz(xxx As String) As String
        Dim funInput As Variant
        Dim funOutput As Variant
            funInput = Array("apple", "apple2", "apple3")   
            'above array- add additional input elements and...
            '...match them with resulting items in below array
            funOutput = Array("orange", "orange2", "apple3") '
    
        zzz = funOutput(Application.Match(xxx, funInput, 0) - 1)
    End Function
    

    VBA 中的函数调用示例:

    Debug.Print zzz("apple2")
    

    将导致:

    orange2
    

    【讨论】:

    • +1 在使用Application.Match 索引数组之前,还没有见过这种方法。创新的。喜欢。
    【解决方案3】:

    如果您只检查一个变量的值,您可以尝试使用 Select Case。这样会更快,因为它会在找到正确的变量后跳过剩余的行。

    Select case xxx
    case "apple"
    zzz = "orange"
    case "apple2"
    zzz = "orange2"
    case "apple3"
    zzz = "orange3"
    End Select
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多