[英]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
這是無需使用Active
和Select
即可完成的工作:
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.