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

我想把每一行都与数字分隔开来,像第二幅图像中的显示一样。

有人可以提供build议。 非常感谢你的帮助。 谢谢

拆分后的数据:

分裂后的数据

分割之前的数据:

分裂前的数据

使用&来连接不同types的数据是很方便的,同时也要求机器确定它处理的是什么types的数据。 这可能不会有太大的不同,但很大程度上取决于例程处理的数据量。

所以,而不是

 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也可以缩短解引用。 下面的改变只会影响一次。 在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