将一行excel工作表复制到另一个

时间:2016-10-06 06:20:17

标签: excel-vba vba excel

我想将选定的行从Sheet1复制到Sheet2。下面的代码覆盖了Sheet2文件中的现有值。请协助停止覆盖我现有的值。

Sub CopySelection()

Dim xlSel As Excel.Range

Set xlSel = Excel.Application.Selection  
xlSel.Copy Excel.Application.Sheets("All_Data").Range("A1")

End Sub

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

下面的代码将复制在“ Sheet1 ”中选择的范围(修改它以适合包含要复制的数据的工作表名称),然后将其粘贴到第一列的A列中工作表“ All_Data ”中的可用行。

如果以下代码(已测试)有效,请告诉我:

Sub CopySelection()

Dim Sht1                As Worksheet
Dim Sht2                As Worksheet
Dim xlSel               As Range
Dim LastRow             As Long

' modify "Sheet1" to your sheet source (where you make your Selection to copy)
Set Sht1 = ThisWorkbook.Sheets("Sheet1")

' sheet "All_Data" is your target sheet (Where you paste the selection)
Set Sht2 = ThisWorkbook.Sheets("All_Data")

Set xlSel = Selection     

'option 1: find last row with data in Sheet "All_Data" at Column A
LastRow = Sht2.Cells(Sht2.Rows.Count, "A").End(xlUp).Row

'option 2: (less reliable) find last row with data in Sheet "All_Data" using UsedRange
'LastRow = Sht2.UsedRange.Rows(Sht2.UsedRange.Rows.Count).Row

' paste the copied range in Column A, the first row after row with data
xlSel.Copy Sht2.Range("A" & LastRow + 1)

End Sub