优化循环多个变量

时间:2018-02-02 11:51:13

标签: arrays excel vba loops for-loop

我有大量的数据,我需要优化这些行,但我根本不知道如何......

" x"将是黑色的所以我不知道如何使用数组而不包括这些空行或如何在没有它们的情况下编写它们。

x,a,b& d是可变数字。

a = Sheets("MODULOS").Range("a1048576").End(xlUp).Row
b = Sheets("TODO").Range("a1048576").End(xlUp).Row

For x = 1 To b
Range("Z1").Select
ActiveCell.Offset(x, 0).Select

For i = 1 To (a - 1)

If ActiveCell.Value <> 0 Then
    d = Sheets("AGREGADO").Range("a1048576").End(xlUp).Row
    Sheets("AGREGADO").Cells(d + 1, 1).Value = Sheets("TODO").Cells(x + 1, 7).Value
    Sheets("AGREGADO").Cells(d + 1, 3).Value = Sheets("TODO").Cells(x + 1, 25 + i).Value
    Sheets("AGREGADO").Cells(d + 1, 2).Value = Sheets("TODO").Cells(1, 25 + i).Value
    Sheets("AGREGADO").Cells(d + 1, 4).Value = Sheets("TODO").Cells(x + 1, 33 + a).Value
End If

    ActiveCell.Offset(0, 1).Select
Next i
Next x

1 个答案:

答案 0 :(得分:2)

有一些方法可以让您的代码更快:

摘要(按重要性排名):

  1. 取消激活自动计算和屏幕更新(如 来自Tomjohnriddle的评论)
  2. 避免。选择 ActiveCell
  3. 使用对象时尽可能使用WITH
  4. 在您的代码中,它看起来像这样:

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    
    Dim ra As Range
    
    a = Sheets("MODULOS").Range("a1048576").End(xlUp).Row
    b = Sheets("TODO").Range("a1048576").End(xlUp).Row
    
    For x = 1 To b
    
    ra = Cells(1 + x, 26)
    
    With Sheets("AGREGADO")
    
    For i = 1 To (a - 1)
    
    If ra.Value <> 0 Then
        d = Sheets("AGREGADO").Range("a1048576").End(xlUp).Row
        .Cells(d + 1, 1).Value = Sheets("TODO").Cells(x + 1, 7).Value
        .Cells(d + 1, 3).Value = Sheets("TODO").Cells(x + 1, 25 + i).Value
        .Cells(d + 1, 2).Value = Sheets("TODO").Cells(1, 25 + i).Value
        .Cells(d + 1, 4).Value = Sheets("TODO").Cells(x + 1, 33 + a).Value
    End If
    
        ra = Cells(1 + x, 26 + 1)
    
    Next i
    Next x
    
    End With
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True