VBA需要太长时间才能运行

时间:2017-10-26 08:34:25

标签: excel excel-vba excel-formula vba

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

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列中的数据。你可以看到一些行包含多行(数字)。

我想将每一行的数字多于一个新行,如第二张图片中的节目。

有人可以建议。非常感谢您的帮助。谢谢

分手后的数据:

Data after split

分割前的数据:

Data before split

1 个答案:

答案 0 :(得分:0)

使用&为了方便地执行不同类型数据的连接,它还要求机器确定它正在处理的数据类型。这可能没有太大的不同,但这在很大程度上取决于例程处理的数据量。

所以而不是

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
相关问题