1

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

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
4

3 回答 3

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
于 2012-12-12T10:02:45.167 回答
1

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

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

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

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
于 2012-12-12T10:02:08.397 回答
1

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

最重要的部分是这个:

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

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

于 2012-12-12T14:05:01.883 回答