【问题标题】:Code to insert n blank cells after every row is very slow在每行之后插入 n 个空白单元格的代码非常慢
【发布时间】:2013-06-19 21:48:24
【问题描述】:

这将是我的代码,但如果我有超过 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

【问题讨论】:

标签: vba optimization excel


【解决方案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 的行数限制之前,这种技术可以处理的记录数(以及可以插入的空白行数)是有限制的。

【讨论】:

  • 太棒了。我遇到了类似的问题,因为 excel 更新显示的速度很慢。很高兴知道我可以简单地将更新设置为 false。
【解决方案2】:

吉米,你的代码非常好。但是如果'A'列没有任何内容而其他列有一些内容,则排序结果会出错。

所以,我将使用 UsedRange 来获取 numberOfValues,如下所示。

 Set r2Arrange = ActiveSheet.UsedRange

A 列中的计数值:

numberOfValues = r2Arrange.Rows.Count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多