这是一个更快的复制方法? Excel VBA

我将会多次重复使用VBA模块的一部分,并且要确保我以最有效的方式执行此操作。 最有效的含义是最快的加载时间。

基本上,我从wb2范围内复制数据并粘贴到wb1目的地。

第一种方法看起来更简单,因为它更短:

wb2.Sheets(1).Range(Cells(2, TrpCdBLCol), Cells(100, TrpCdBLCol)).Copy wb1.Sheets("BL Import").Cells(2, TrpCdCol) 

第二种方法我声明两个variables作为范围,设置它们和副本

 Dim CopyRange As Range, Dest As Range Set CopyRange = wb2.Sheets(1).Range(Cells(2, TrpCdBLCol), Cells(100, TrpCdBLCol)) Set Dest = wb1.Sheets("BL Import").Cells(2, TrpCdCol) CopyRange.Copy Dest 

有没有什么区别,或比其他方式更好? 谢谢!

您可以从范围1到范围2获得相同的内容,而不需要复制和粘贴:

  1. 在Range1中直接设置Range1(此方法复制值,可用于计算公式,但不能格式化)
  2. 使用变体数组(添加一个步骤)

在我的testing中,第一个选项在第二个时间的2/3处运行 – 这是由于额外的步骤。

更新:高效的技术

  • 在使用Long而不是Integer时 , 为什么使用Integer而不是Long?
  • 在使用Value2而不是Value时 ,请参阅Charles Williams的post
  • 如果您正在操作数据并将其写回工作表,请使用变体数组,而不是范围对象。 如果你正在使用string,那么这里是有效编码的一站式参考

选项1

 Sub Recut1() Dim ws1 As Worksheet Dim ws2 As Worksheet Dim TrpCdBLCol As Long TrpCdBLCol = 1 Set ws1 = Sheets(1) Set ws2 = Sheets(2) vArr = ws1.Range(ws1.Cells(2, TrpCdBLCol), ws1.Cells(100, TrpCdBLCol)) ws2.Range(ws2.Cells(2, TrpCdBLCol),ws2.Cells(100, TrpCdBLCol)).Value2 = vArr End Sub 

选项2

 Sub Recut2() Dim ws1 As Worksheet Dim ws2 As Worksheet Dim TrpCdBLCol As Long Set ws1 = Sheets(1) Set ws2 = Sheets(2) TrpCdBLCol = 1 ws2.Range(ws2.Cells(2, TrpCdBLCol), ws2.Cells(100, TrpCdBLCol)).Value2 = ws1.Range(ws1.Cells(2, TrpCdBLCol), ws1.Cells(100, TrpCdBLCol)) End Sub 

2个选项之间唯一的(非常轻微的)性能差异是第二个将执行另外创build2个Range对象的额外操作

与复制数据时的性能有关的主要考虑因素是,如果您需要格式化单元格(颜色,字体等),这需要在幕后进行大量工作,但最好自己来完成。 如果您不需要格式化,您立即获得显着的性能提升

为了可维护性,第二个选项更好,但是你也应该明确地使用所有的对象(包括Cells()),并完全绕过剪贴板。 另外,不需要重复代码:创build一个以2个工作表为参数的共享子文件

 Option Explicit Public Sub copyData(ByRef wsFrom As Worksheet, ByRef wsTo As Worksheet) With wsFrom Set copyRange = .Range(.Cells(2, TrpCdBLCol), .Cells(100, TrpCdBLCol)) End With With wsTo Set destRange = .Range(.Cells(2, TrpCdBLCol), .Cells(100, TrpCdBLCol)) End With destRange.Value2 = copyRange.Value2 End Sub 

并使用此行从您需要的任何工作表调用它:

 copyData wb2.Worksheets(1), wb1.Worksheets("BL Import") 

我可能会完全跳过复制,并使用数组。 例如:

 Sub CopyWithoutCopying() Dim MyArr As Variant MyArr = Application.Transpose(Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)) Sheets("Sheet2").Range("A1").Resize(UBound(MyArr), 1) = Application.Transpose(MyArr) End Sub 

这会将列A中的数据复制到名为Sheet2列A的表中