如何在将数据复制并粘贴到新工作表

时间:2017-03-02 12:48:46

标签: excel vba excel-vba

我创建了一个宏来复制一张工作表中的数据并将数据转置并粘贴到另一张工作表中,如下所示:

Sub sbCopyRangeToAnotherSheet()

    'Copy the data
    Sheets("Raw Data").Range("A4:A27").Copy
    'Transpose and paste data to new sheet
    Sheets("Distinct Users").Range("D6:AA6").PasteSpecial Transpose:=True

End Sub

我需要这样做31次,我不太清楚如何做到这一点。我假设我需要在Range中使用.offset功能,但我不知道该怎么做...

例如,我需要将我复制的初始范围(“A4:A27”)更改为(“A28:A51”),然后将粘贴范围更改为(“D7:AA7”)。

我想过创建一个变量来定义起始单元格,另一个变量来定义该范围的结束单元格,然后使用offset来增加循环内部的偏移量。我最大的问题是......我不确定如何为我的偏移量定义起始单元格和结束单元格!另外,我不确定我是否可以做类似的事情:

Dim lwrRange1 as Cell = "A4"
Dim uprRange1 as Cell = "A27"
Dim lwrRange2 as Cell = "D6"
Dim uprRange2 as Cell = "AA6"

Do While 1 <= 31
   'Copy the data
    Sheets("Raw Data").Range(lwrRange1:uprRange1).Copy
    'Transpose and paste data to new sheet
    Sheets("Distinct Users").Range(lwrRange2:uprRange2).PasteSpecial Transpose:=True
    lwrRange1 += 24
    uprRange1 += 24
    lwrRange2 += 1
    uprRange2 += 1
    i += 1
Loop

非常感谢任何帮助或见解!

2 个答案:

答案 0 :(得分:3)

也许尝试使用For循环:

    Sub sbCopyRangeToAnotherSheet()
Dim i As Integer
Dim rCopy As Range, rPaste As Range

Set rPaste = Sheets("Distinct Users").Range("D6:AA6")
Set rCopy = Sheets("Raw Data").Range("A4:A27")

For i = 0 To 30
    'Copy the data
    rCopy.Offset(rCopy.Rows.Count * i, 0).Copy
    'Transpose and paste data to new sheet
    rPaste.Offset(rPaste.Row + i, 0).PasteSpecial Transpose:=True
Next i

End Sub

答案 1 :(得分:2)

使用范围对象:

Dim SrcRg As Range
Dim DestRg As Range

Set SrcRg = Sheets("Raw Data").Range("A4:A27")
Set DestRg = Sheets("Distinct Users").Range("D6")

For i = 1 To 31
   'Copy the data
    SrcRg.Copy
    'Transpose and paste data to new sheet
    DestRg.PasteSpecial Transpose:=True
    Set SrcRg = SrcRg.Offset(SrcRg.Rows.Count, 0)
    Set DestRg = DestRg.Offset(1, 0)
Next i