简体   繁体   中英

Copy Data from one Excel Workbook to Another Workbook in Last row

I am Trying to run this Code, which will copy the Source sheet Row to Destination Sheet last Row, but my this code giving error 400 while compiling,

Advance Thanks for Help

Sub CopyData()
    Dim sBook_t As String
    Dim sBook_s As String

    Dim sSheet_t As String
    Dim sSheet_s As String

    On Error GoTo Errorcatch

    sBook_t = "C:\Users\Unknown\Desktop\Free\Calculators.xlsx"
    Workbooks.Open (sBook_t)
    sBook_s = "C:\Users\Unknown\Desktop\Free\PRODUCT_35.xlsm"
    Workbooks.Open (sBook_s)

    sSheet_t = "cstdatalist"
    sSheet_s = "cstdata"

    Sheets(sSheet_s).Range("A2").Copy Destination:=Sheets(sSheet_t).Range("A2")
End Sub

Have a try on following sub.

Sub CopyData()
Dim wb As Workbook
Dim sht, shtLocal As Worksheet
Dim rngPaste As Range
Dim rngLastData, wbPath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False

    wbPath = "D:\dBook.xlsx"
    Set wb = Workbooks.Open(wbPath)
    Set sht = wb.Sheets(1)
    Set shtLocal = ThisWorkbook.Sheets("Sheet1")
    Set rngPaste = sht.Cells(Rows.Count, 1).End(xlUp).Offset(1) 'Destination range set after last used cell of column A

    rngLastData = shtLocal.Cells(Rows.Count, "A").End(xlUp).Address
    shtLocal.Range("A1:" & rngLastData).Copy rngPaste

    wb.Save
    wb.Close
    Set sht = Nothing
    Set shtLocal = Nothing
    Set rngPaste = Nothing

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

enter code here Here is my adjustment of your code. What I did is declared the workbooks and the worksheets separately. This way it is clear which workbook/sheet is the source and which is the destination.

  Sub CopyData()
        Dim sBook_t As String
        Dim sBook_s As String
        Dim workbook_t As Workbook
        Dim sSheet_t As Worksheet
        Dim sSheet_s As Worksheet


    Dim sSheet_t As String
    Dim sSheet_s As String

    On Error GoTo Errorcatch

    sBook_t = "C:\Users\Unknown\Desktop\Free\Calculators.xlsx"
      set workbook_t =  Workbooks.Open (sBook_t)
    sBook_s = "C:\Users\Unknown\Desktop\Free\PRODUCT_35.xlsm"
      set workbook_s =  Workbooks.Open (sBook_s)

   set sSheet_t = workbook_t.Sheets("cstdatalist")
   set sSheet_s = workbook_s.Sheets("cstdata")

    sSheet_s.Range("A2").Copy Destination:=sSheet_t.Range("A2")


    End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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