繁体   English   中英

Excel VBA复制/粘贴范围从1个工作表到另一个,每次相同的范围粘贴到下一个目标列

[英]Excel VBA copy/paste range from 1 worksheet to another, same range pastes in next destination column each time

我是Excel VBA的新手。

我正在尝试将一个工作表中的一系列数据复制到同一工作簿中的另一个工作表中。

因此,在Sheet1中复制range(“ A2:B10”),然后在Sheet2中粘贴(“ A2”)。

每次运行宏时,我都希望将(“ Sheet 1”)。Range(“ A2:B10”)中的值粘贴到连续的列中,因此在本例中是在Sheet 2中的“ B2”中。

谢谢你的帮助!

我有第一部分,但为第二部分而苦苦挣扎:

Sub sbCopyRangeToAnotherSheet()
'Set range
Sheets("Sheet1").Range("A2:B10").Copy  Destination:=Sheets("Sheet2").Range("A2")
'Copy the data
Sheets("Sheet1").Range("A2:B10").Copy
'Activate the destination worksheet
Sheets("Sheet2").Activate
'Select the target range
Range("A2").Select
'Paste in the target destination
ActiveSheet.Paste

Application.CutCopyMode = False
End Sub

您的代码很奇怪

此行Sheets("Sheet1").Range("A2:B10").Copy Destination:=Sheets("Sheet2").Range("A2")将所有内容复制并粘贴到一行中。 因此,您在.copy .activate .select.paste之后的行是多余的。 您的第一行已经完成了所有这一切。

您需要标识Sheet2的行“ A”中最后使用的列。 为此,可以使用范围的.End()方法查找该行中的第一个占用的单元格。 然后将该单元格用作复制Destination

 Sub sbCopyRangeToAnotherSheet()

     'Declare a variable to hold the cell to which we will paste the data
     Dim pasteCell as Range

     'Set the variable to the first empty cell in Row 2
     Set pasteCell = Sheets("Sheet2").Range("IV2").end(xlToLeft).Offset(,1)

     'Copy and paste
     Sheets("Sheet1").Range("A2:B10").Copy  Destination:=pasteCell
End Sub

这是无需使用ActiveSelect即可完成的工作:

Option Explicit

Sub TestMe()

    Dim ws1         As Worksheet
    Dim ws2         As Worksheet        
    Dim source      As Range
    Dim target      As Range        
    Dim lastColumn  As Long

    Set ws1 = Worksheets(1)
    Set ws2 = Worksheets(2)

    With ws2
        lastColumn = .Cells(2, .Columns.Count).End(xlToLeft).Column
        If WorksheetFunction.CountA(.Columns(1)) > 0 Then
            lastColumn = lastColumn + 1
        End If
    End With

    Set source = ws1.Range("A2:A10")
    Set target = ws2.Cells(2, lastColumn)

    source.Copy destination:=target
    Application.CutCopyMode = False

End Sub

代码中最棘手的部分是开始在目标工作表的正确列上编写。 如果工作表为空,则正确的列是第一列。 在其他情况下,正确的列是最后一列+ 1。

查找最后使用的列的标准方法Range.End(xlToLeft).Column始终将第一列作为最后使用的列返回,而无需注意是否使用了它。 因此,您需要进行某种检查以了解其是否为空: WorksheetFunction.CountA(.Columns(1)) > 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM