代码 运行 比其他文件/日期慢

Code running more slowly than on other files / dates

我 运行 下面的代码循环了 6500 个条件单元格,这些单元格是根据引用的 "LISTS" 选项卡中包含的 运行ge 查找的。这个 运行ge 大约有 2 万行。

我昨天在一个测试文件中多次 运行 代码并且它 运行 非常快。也许 2 分钟:如果那样。

今天,在确定我对代码感到满意之后,我将其粘贴到我的主要项目中(在此处加盖,因为我想知道这是否与它有关)。 现在当我运行代码时,需要2个小时以上!

除 sheet 个名称外,我没有更改任何代码。

有人知道我失踪的原因吗?

我是 VBA 的新手,所以我怀疑这是某个地方的菜鸟错误!

Dim x As Long
x = WorksheetFunction.CountA(Columns(1))

'define string length for CELL loop
Dim char As Integer
char = Len(ActiveCell)

'define cell loop name
Dim counter As Integer

'Begin RANGE loop
For Each cell In Range("b1:b" & x)
    cell.Activate

    'Incorporate CELL loop
    For counter = 1 To char
        'Determine if numeric value present in cell = TRUE or FALSE
        If IsNumeric(Right(Mid(ActiveCell, 1, counter), 1)) = True Then
            ActiveCell.Offset(0, 1).Value = Right(ActiveCell.Offset(0, 0), Len(ActiveCell.Offset(0, 0)) - counter + 1)
            Exit For
        Else
            ActiveCell.Offset(0, 1).Value = ActiveCell.Offset(0, 0)
        End If
    Next
Next

您需要避免 ActiveCell,因为它会减慢您的代码速度。您正在使用 for-each 循环,因此您可以像这样在循环中使用变量:

For Each cell In Range("b1:b" & x)
    For counter = 1 To char
        If IsNumeric(Right(Mid(cell, 1, counter), 1)) = True Then
            cell.Offset(0, 1).Value = Right(cell, Len(cell) - counter + 1)
            Exit For

        Else
            cell.Offset(0, 1) = cell.Offset(0, 0)

        End If
    Next
Next

此外,cell.Offset(0, 0)之类的东西有点没用。如果不需要Offset,就不要写了。总的来说:

  • How to avoid using Select in Excel VBA

  • How To Speed Up VBA Code

尝试下面的代码,代码注释中的解释:

Dim x As Long
Dim char As Long 'define string length for CELL loop
Dim counter As Long 'define cell loop name

x = WorksheetFunction.CountA(Columns(1))

Application.ScreenUpdating = False ' will make your code run faster
Application.EnableEvents = False


'Begin RANGE loop
For Each cell In Range("b1:b" & x)
    'cell.Activate ' <--- no need to Activate, realy slows down your code

    'Incorporate CELL loop
    For counter = 1 To char

        'Determine if numeric value present in cell = TRUE or FALSE
        If IsNumeric(Right(Mid(cell.Value, 1, counter), 1)) = True Then
            cell.Offset(0, 1).Value = Right(cell.Value, Len(cell.Value) - counter + 1)
            Exit For
        Else
            cell.Offset(0, 1).Value = cell.Value
        End If
    Next counter
Next cell

Application.ScreenUpdating = True
Application.EnableEvents = True

感谢所有花时间参与 post 的人。 原来我是白痴!!!

我第一次 运行 代码时,我禁用了自动计算,而在我 re-running 这段时间里,我把它注释掉了。

我是 VBA 的新手,但这没有任何借口!啊!

因此,修复(正如其他人在线程中所建议的那样):

在宏主体之前输入:

Application.Calculation = xlCalculationManual

然后在宏后输入:

Application.Calculation = xlCalculationAutomatic