vba - 在每行后插入 n 个空白单元格的代码非常慢

标签 vba optimization excel

这将是我的代码,但如果我有超过 5000 行和 1 列,则需要花费一生的时间。有没有办法减少查询时间?

Sub InsertRows() 
    Dim numRows As Integer 
    Dim r As Long 

    Application.ScreenUpdating = False 

    r = Cells(Rows.Count, "A").End(xlUp).Row 
    numRows = 11 

    For r = r To 1 Step -1 
        ActiveSheet.Rows(r + 1).Resize(numRows).Insert 
    Next r 

    Application.ScreenUpdating = True 
End Sub

最佳答案

这花了 <1 秒。

Sub InsertRows()

Dim numberOfValues As Long
Dim i As Long
Dim values As Variant

Const numberOfEmptyRows As Long = 11

Application.ScreenUpdating = False

' count values in column A
numberOfValues = Cells(Rows.Count, "A").End(xlUp).Row

' populate array with numbers
ReDim values(1 To numberOfValues, 1 To 1)
For i = 1 To numberOfValues
  values(i, 1) = i
Next i

' I know there is a better way to do this part...
Range(Cells(1, 2), Cells(numberOfValues, 2)).Value = values
For i = 1 To numberOfEmptyRows - 1
  Range(Cells(Rows.Count, "B").End(xlUp).Offset(1, 0), Cells(Rows.Count, "B").End(xlUp).Offset(numberOfValues, 0)).Value = values
Next i

' sort by values inserted in column B
Range(Cells(1, 1), Cells(Rows.Count, "B").End(xlUp)).Sort Key1:=Range("B1"), _
        Order1:=xlAscending, Header:=xlGuess, _
        OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
        DataOption1:=xlSortNormal

Columns("B:B").EntireColumn.Delete

Application.ScreenUpdating = True
End Sub

此代码使用辅助列(在本例中为 B)在目标范围旁边插入数字序列。然后,它在自身下方添加相同的数字 N 次,并对该列进行排序。最后,它删除该列。通过这种方式,您可以快速将空白行插入到任何数据集中。

如果要插入更多/更少的空白行,请更改 Const numberOfEmptyRows As Long = 11。在达到 Excel 的行限制之前,此技术可以处理的记录数(以及可以插入的空白行数)是有限的。

关于vba - 在每行后插入 n 个空白单元格的代码非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11559590/

相关文章:

vba - Excel VBA-Duplicates 使用按钮/添加位置运行

excel - 使用 VBA 和数组公式方法的 VLookup with Multiple Criteria

vba - 如何在 VBA 中创建列表(而不是字典)?

c# - 如何在 MVC 中使用 EPPlus 从服务器下载 .xlsx 文件

regex - Visual Basic Excel 正则表达式 {}

excel - 将标题分成单词并在标题中搜索

c# - 禁用特定函数或代码块的编译器优化 (C#)

performance - 加权 Gram-Schmidt 正交化的 MATLAB 优化

c - 哪个更有效率?重复分配或重复检查

excel - 从 0 开始 for 循环(而不是 1)