VBA功能避免如果声明

时间:2013-06-20 20:28:12

标签: vba if-statement

我正在构建一个非常复杂的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个字符串代替)。我多次调用此函数。有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

几乎没有。而对于30个字符串,这应该不是非常慢。

性能问题很可能出现在另一个地方,特别是在您直接与工作簿交互的地方。在随机尝试更新代码片段之前,尝试测量各种过程的时间。

很多行并不意味着性能下降。并非每条线都需要相同的时间来执行。

答案 1 :(得分:1)

您可以使用数组和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

答案 2 :(得分:1)

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

Select case xxx
case "apple"
zzz = "orange"
case "apple2"
zzz = "orange2"
case "apple3"
zzz = "orange3"
End Select
相关问题