复制粘贴Excel VBA代码的说明

时间:2012-12-12 09:42:58

标签: excel vba excel-vba

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

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

3 个答案:

答案 0 :(得分:4)

请注意,发布的代码会将特定范围从最后一张纸张复制到最后一张纸张

' Basically it is copying the VALUE (There are other things to copy, e.g. 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

答案 1 :(得分:1)

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

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

最后,您还可以使用类似的方法将范围“复制”到可以处理的变量。即,使用示例中的预定义范围:

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

答案 2 :(得分:1)

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

最重要的部分是这一个:

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

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