【问题标题】:VBA Takes Too Long to RunVBA 运行时间过长
【发布时间】:2018-04-07 13:08:26
【问题描述】:

下面的代码很好,唯一的问题是处理时间太长。 有谁知道如何加快速度?

Public Sub separate_line_break()

target_col = "H"     'Define the column you want to break
delimiter = Chr(10)   'Define your delimiter if it is not space
ColLastRow = Range(target_col & Rows.Count).End(xlUp).Row

Application.ScreenUpdating = False

For Each Rng In Range(target_col & "1" & ":" & target_col & ColLastRow)
    If InStr(Rng.Value, delimiter) Then
        Rng.EntireRow.Copy
        Rng.EntireRow.Insert
        Rng.Offset(-1, 0) = Mid(Rng.Value, 1, InStr(Rng.Value, delimiter) - 1)
        Rng.Value = Mid(Rng.Value, Len(Rng.Offset(-1, 0).Value) + 2, Len(Rng.Value))
    End If
Next

ColLastRow2 = Range(target_col & Rows.Count).End(xlUp).Row

For Each Rng2 In Range(target_col & "1" & ":" & target_col & ColLastRow2)
    If Len(Rng2) = 0 Then
        Rng2.EntireRow.Delete
    End If
Next

Application.ScreenUpdating = True

End Sub

我想要实现的是根据行拆分 F 列中的数据。你可以看到有些行包含不止一行(数字)。

我想将每行编号超过 1 的每一行分隔成一个新行,如第二张图片所示。

有人可以请教。非常感谢您的帮助。谢谢

拆分后的数据:

拆分前的数据:

【问题讨论】:

  • Speed up the VBA code的可能重复
  • 您可以将整个范围读入一个变体数组 (Arr=rng.value2),在数组中执行所有操作,然后一步将其写回。这应该更快(我敢打赌 100 倍左右)。如果您遇到问题,请回来。
  • 您好 Jochen,我不是程序员,如果您能帮我修改代码,不胜感激。我在网上找到了代码并自己修改了它,但完全不知道如何实现您的建议。

标签: excel excel-formula vba


【解决方案1】:

虽然使用 & 来连接不同类型的数据很方便,但它也需要机器确定它正在处理的数据类型。这可能没什么不同,但这在很大程度上取决于例程处理的数据量。

所以不是

For Each Rng In Range(target_col & "1" & ":" & target_col & ColLastRow)

使用

For Each Rng In Range(target_col + "1" + ":" + target_col + CStr(ColLastRow))

另外,不要连接文字。所以不是

For Each Rng In Range(target_col + "1" + ":" + target_col + CStr(ColLastRow))

使用

For Each Rng In Range(target_col + "1:" + target_col + CStr(ColLastRow))

使用 With/End With 也可以稍微缩短取消引用。以下更改仅尊重 Rng 一次。在 Rng2 循环中使用相同的方法。

For Each Rng In Range(target_col + "1:" + target_col + CStr(ColLastRow))
    With Rng
        If InStr(.Value, delimiter) Then
            .EntireRow.Copy
            .EntireRow.Insert
            .Offset(-1, 0) = Mid(.Value, 1, InStr(.Value, delimiter) - 1)
            .Value = Mid(.Value, Len(.Offset(-1, 0).Value) + 2, Len(.Value))
        End If
    End With
Next

看起来你的循环只会迭代一次,所以你可以一起取消循环。

With Range(target_col + "1:" + target_col + CStr(ColLastRow))
    If InStr(.Value, delimiter) Then
         .EntireRow.Copy
        .EntireRow.Insert
        .Offset(-1, 0) = Mid(.Value, 1, InStr(.Value, delimiter) - 1)
        .Value = Mid(.Value, Len(.Offset(-1, 0).Value) + 2, Len(.Value))
    End If
End With

【讨论】:

  • 您好,感谢您的解决方案。它似乎工作。我可以从 20+ 秒减少到 13 秒。但是我无法实现最后一个代码。它显示“类型不匹配”错误。感谢您是否可以提供完整的修改代码。非常感谢您的宝贵时间。
猜你喜欢
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 2015-09-29
  • 2020-06-02
相关资源
最近更新 更多