VBA (Excel) 插入多行的方法 & 算法对比

本文记录,通过 Excel VBA,插入多行的方法;以插入500行为例,来对比算法上的优劣;是一次很典型的,对算法的阐述;面向小白,言简意赅 (^_^)


方法 1 (普通):

这种方式是最直观,但也是最慢的方法;原理就是,一行一行的插入;插入500行,大约要 27.34375 秒;非常的慢!Big O = O(n) = 500;

' insert 500 rows in sheet, with loop
For i = 1 To 500
    Rows(Selection.Row).Insert
Next

方法 2 (算法):

这种方法的精彩之处在于算法;它远快于 "方法1",但还不是最快的!大约要 0.5390625 秒;这种方法的 Big O = O (logN+1) = log500+1 = 9;

' insert 500 rows in sheet, with algorithm
cum_multiplier = 1
For i = 1 To 500
    If cum_multiplier * 2 < 500 Then
        Rows(Selection.Row & ":" & (Selection.Row + cum_multiplier - 1)).Insert
        cum_multiplier = cum_multiplier * 2
    Else
        rows_remain = 500 - cum_multiplier
        Rows(Selection.Row & ":" & (Selection.Row + rows_remain)).Insert
        Exit Sub
    End If
Next

方法 3 (最快):

这种方法使用的是 VBA 中,Range.Resize() 方法;代码长度,只有一行;速度也最快,只需 0.078125 秒,但是插入点下面的行越多,花费的时间就越长;从算法的角度来看 Big O = O(1) = 1;

' insert 500 rows in sheet, with Range.Resize()

' insert with format copied
ActiveCell.EntireRow.Offset(1).Resize(500).Insert Shift:=xlDown

' insert without format copied
ActiveCell.EntireRow.Resize(500).Insert

方法 4 (便利):

这种方法使用的是 VBA 中,Range().EntireRow.Insert 方法,和 Rows().Insert 方法;代码也只有 一行;速度也只需 0.078125 秒,但是插入点下面的行越多,花费的时间就越长;同上,从算法的角度来看 Big O = O(1) = 1;这种方法的好处是,可以指定要从哪行开始插入,是一个额外的方便之处。

' insert 500 rows in sheet, from specified row

' insert rows with Range().EntireRow.Insert method 
Range("12:512").EntireRow.Insert 

' insert rows with Rows().Insert method 
Rows(12 & ":" & 512).Insert
' or with variable
Rows(Selection.Row & ":" & (Selection.Row + 500)).Insert

篇尾总结:

文中记述的方法,是比较简单,是一个不错的知识点记录;但更重要的是,用这简单的代码,讲述了算法的意义,和 big O 的概念。文章面向初学者,希望对大家有帮助;小白贡献,语失莫怪,开心每一天 (^_^)~~~


我的博客:

请来关注吧 (^_^)v Bitssea: www.cnblogs.com/bitssea


原文地址:https://www.cnblogs.com/bitssea/p/15135750.html