copy sheet content to another sheet

安稳与你 提交于 2020-01-15 14:09:50

问题


I want to copy the content of one sheet at the end of the other, i have tried this vba code and it works,

Private Sub CommandButton1_Click()
Sheets("B").Select
Range("A1:H14").Select
Range("A1:H14").Copy

Sheets("A").Select
' Find the last row of data
Range("B48:I48").Select
ActiveSheet.Paste
Sheets("A").Select
End Sub

but what i want is to copy without having to specify the range of the data, because i have many files and many data and it's gonna be hard to do all of that manually and change the range a each time.


回答1:


There's no need to use so many Select, which slows down the code, you can use the 1 line below will copy the entire contents of Sheet("B") to the first empty row at Column "A" in Sheet("A").

Dim Rng             As Range
Dim lRow            As Long
Dim lCol            As Long
Dim lPasteRow       As Long

With Sheets("B")

    lRow = .Cells.Find(What:="*", _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Row

    lCol = .Cells.Find(What:="*", _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Column

    lPasteRow = Sheets("A").Cells.Find(What:="*", _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Row

    .Range(.Cells(1, 1), .Cells(lRow, lCol)).Copy Destination:=Sheets("A").Range("A" & lPasteRow + 1)
End With



回答2:


Below will copy entire content in Sheet B to Sheet A

Sheets("B").Cells.Copy Destination:=Sheets("A").Range("A1")

You do not need to select cells while copying.




回答3:


I usually do something like this, assuming sheet1 is the sheet to be updated by data from sheet2;

dim destLen as Long 'rows used in sheet 1
dim sourceLen as Long 'rows used in sheet 2

Open directory with source files and loop through each file and do the following

destLen = Sheet1.Range("A"&Rows.Count).End(xlUp).Row
sourceLen = Sheet2.Range("A"&Rows.Count).End(xlUp).Row
Sheet2.Range("B1" & ":I" & sourceLen).copy
Sheet1.Range("A" & destLen + 1).pasteSpecial xlValues
Application.CutCopyMode = False


来源:https://stackoverflow.com/questions/43468467/copy-sheet-content-to-another-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!