复制粘贴Excel VBA代码的说明

这是我在互联网上find的代码,但我不想用它,而我不知道它是如何运作的,所以想问问是否有人可以为我解释它?

Sub CopyPaste() Dim sh As Worksheet, Src As Range, Dst As Range For Each sh In Application.Worksheets If sh.Index <> Worksheets.Count Then Set Src = sh.Range("A1:L34") Set Dst = Worksheets(3).Range("A500").End(xlUp).Offset(1, 0).Resize(Src.Rows.Count, Src.Columns.Count) Dst.Value = Src.Value End If Next sh End Sub 

请注意,发布的代码将复制从EACH表格到LAST的指定表格的指定范围

 ' Basically it is copying the VALUE (There are other things to copy, eg format, color) ' from the Source Range from all worksheet(s) to the Destination Range on another worksheet Sub CopyPaste() 'The beginning of subroutine, you cannot return value in SubRoutine, and you can't call subroutine directly from Excel worksheet formula Dim sh As Worksheet, Src As Range, Dst As Range 'declaring each variable 'You can look up each object in Object Explorer by F2 in VB Editor For Each sh In Application.Worksheets 'iterate though each worksheet in all workbooks If sh.Index <> Worksheets.Count Then 'if this sheet isn't the last sheet Set Src = sh.Range("A1:L34") 'set Src variable to the src range Set Dst = Worksheets(3).Range("A500").End(xlUp).Offset(1, 0).Resize(Src.Rows.Count, Src.Columns.Count) 'Worksheets(3) <-- a specific target worksheet '.Range("A500").End(xlUp).Offset(1, 0) <-- trying to find the last empty cell bottom up from cell A500 '.Resize(Src.Rows.Count, Src.Columns.Count) <-- Resizing the range so that it fits with src range Dst.Value = Src.Value 'Assign the value of all cells in the dst range from src range End If Next sh End Sub ' The end of subroutine 

您使用此代码所做的所有操作都将目标范围的值设置为源范围的值。 你不是在正常意义上“复制”单元格,因为你不会像使用正常的复制和粘贴(即通过执行Crtl + C和Crtl + V)那样保留源单元格的任何格式。

然而,这种方法有其优点,因为它比编码复制和粘贴速度快得多,所以如果它是更有效率之后的值。

最后,还可以使用类似的方法将范围“复制”到可以处理的variables。 即在你的例子中使用你的预定义范围:

 Dim vVar as Variant vVar = Src.value for ii = lBound(vVar, 1) to uBound(vVar, 1) for jj = lBound(vVar, 2) to uBound(vVar, 2) vVar(ii, jj) = vVar(ii, jj) + 1 next jj next ii Dst.Value = vVar 

使用此代码,您可以将范围A1:L34从所有工作表复制到第三个工作表 (除了最后一个工作表不会复制)。

最重要的部分是这一个:

 Set Dst = Worksheets(3).Range("A500").End(xlUp).Offset(1, 0).Resize(Src.Rows.Count, Src.Columns.Count) 

这里设定目的地范围 。 对于每个复制的工作表,目标范围是偏移的 ,因此复制的数据在粘贴后不会重叠