0

您好,我有一个问题,下一个代码树在 VBA 中的效率更高

选项1:

While fin 

    if activecell.value = "Comp"
        ' do something 
        ' I use some many time the value of the activecell or the line 
        ' im actually
    end if

    activecell.offset(1,0).activate

loop

选项 2:

dim i as long
i=0

While fin 

    if activecell.offset(i,0).value = "Comp"
        ' do something 
        ' I use some many time the value of the activecell or the line 
        ' im actually
    end if

    i = i + 1
loop

选项3:'因为我使用了很多次我不知道的实际行'如果将这个值带到变量中可能会更好

dim i as long
dim x as string
i=0

While fin 

    x = activecell.offset(i,0)

    if x = "Comp"
        ' do something 
        ' I use some many time the value of the activecell or 
        'the line im actually
    end if

    i = i + 1
loop

在此先感谢您的帮助

PD FOR我所有的代码

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
Application.DisplayAlerts = False
4

2 回答 2

3

选项4,即你没有写的选项4,比你的选项1-3效率高得多。不要费心激活或抵消任何细胞。只需将您的数据加载到 Variant 数组中,然后对其进行操作。

Dim v As Variant
Dim i As Long

v = Sheet1.Range("A1:A1000").Value ' or wherever your data is

For i = 1 To UBound(v, 1)
    If v(i, 1) = "Comp" Then
        ' do something
    End If
Next i
于 2012-11-21T11:32:04.913 回答
2

选项 2。

使用选项 1,您将在每次迭代时激活单元格,这是不必要的。选项 3 您正在设置一个变量,但只使用一次,因此设置中有成本,但在初始检查之外没有用处。

此外,在检查使用 Value2 时,它不会检查货币/日期,并且字符串将比当前使用的隐式 .Value 更快:

if activecell.offset(i,0).Value2 = "Comp"
于 2012-11-21T10:37:30.567 回答