2

我编写了一些运行速度很慢的 VBA 代码。我的代码中有一系列不同的循环。我知道循环并不总是处理数据的最有效方式,所以我认为它们是问题所在。我需要有关如何更改或消除循环的想法,以便加快代码的运行时间。

下面是我创建的最活跃的循环。它遍历 D 行(从 D2 开始)上的所有单元格,并根据第 1 行单元格中的条目来操作它们的值。如果我能在这个循环上获得帮助,我可能能够使用类似的技术来改变我的代码中的其他循环。任何提示表示赞赏。

'sub work week for date range
     Range("D2").Select
     Do Until IsEmpty(ActiveCell.Value)
         If IsEmpty(ActiveCell.Offset(-1, 0)) = False Then
             ActiveCell.Value = ActiveCell.Offset(-1, 0).Value & "-" & Right(ActiveCell.Value, 4)
         Else: ActiveCell.Value = ActiveCell.Value & "-" & Right(ActiveCell.Offset(0, -1), 4)
         End If
     ActiveCell.Offset(0, 1).Select
Loop
4

2 回答 2

1

最快、更有效的方法是评论中建议的使用数组。

不过,为了让您达到这一点,我已经为您提供了改进与 VBA 交互并了解如何在不选择或激活对象的情况下编写代码的第一步:

For i = 4 To Cells(2, Columns.Count).End(xlToLeft).Column
    With Cells(2, i)
        If .Offset(-1, 0).Value = vbNullString Then
            .Value = .Value & "-" & Right$(.Offset(0, -1).Value, 4)
        Else
            .Value = .Offset(-1, 0).Value & "-" & Right$(.Value, 4)
        End If
    End With
Next

基本上,你不需要.Select.Activate任何东西。直接使用对象并使用变量来指示列,而不是激活下一个单元格。

一旦您对以这种风格编写代码感到满意,请考虑将范围的值分配给 2D 数组,然后循环遍历该数组。

于 2017-08-04T14:28:09.577 回答
0

为了快速执行,我的第一个建议是如果仍然需要很长时间,也关闭自动计算和屏幕更新。

我同意任何涉及选择的事情都会非常慢,所以你应该使用范围对象。

最终代码:

' Declarations
Dim CurrentCell, LeftCell, PreviousCell As Range
Dim Last4Chars As String

'Initialize
Set CurrentCell = ActiveSheet.Range("D2")

'Optimizations
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

'Loop until Current Cell in Empty
Do Until IsEmpty(CurrentCell.Value)
    Set AboveCell = CurrentCell.Offset(-1, 0)        'One row above
    Set LeftCell = CurrentCell.Offset(0, -1)         'One column left

    If IsEmpty(AboveCell) = False Then
        CurrentCell.Value = AboveCell.Value & "-" & Right(CurrentCell.Value, 4)
    Else
        CurrentCell.Value = CurrentCell.Value & "-" & Right(LeftCell, 4)
    End If

    Set CurrentCell = CurrentCell.Offset(0, 1)
Loop

'Optimizations reversed for normal use
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
于 2017-08-04T14:58:38.793 回答