Copy the data from one Excel workbook to another using vba

Elena Margulis

New Member
Joined
Aug 21, 2020
Messages
25
Office Version
  1. 365
Platform
  1. Windows
I have Book1 workbook with some dataset inside (it can be any records amount dataset), but always starts from cell A1
I need to copy the content of the Book1, which is located in Sheet1 into my other workbook Book2, Sheet1 using macro or vba - by pressing any short key (when macro will be executed)

I was trying to use the following code (advice from another site + research), but having an error - Microsoft Visual Basic for Application, 400

Please, help...

VBA Code:
Option Explicit

Sub OpenWorkbook()

    Dim swb As Workbook
    Set swb = Workbooks.Open("E:\Projects\AAA\Book1.xlsx")
    Dim sws As Worksheet: Set sws = swb.Worksheets("Sheet1")
    Dim srg As Range: Set srg = sws.Range("All Data")

    Dim dwb As Workbook
    Set dwb = Workbooks.Open("E:\Projects\AAA\Book2.xlsm")
    Dim dws As Worksheet: Set dws = dwb.Worksheets("Sheet1")
    Dim dCell As Range: Set dCell = dws.Range("A1")

    srg.Copy dCell
 

    swb.Close SaveChanges:=False
    dwb.Save

End Sub
 
Last edited:
The code only works when opening file and after that not work. If you wantto see modification do after changing at book1 you have two option.
1. Add 2nd code at that post to Book2
Or
2. Add same code as code1 to book1 again but first line should be
Before_Close Not Open
thank you; clearcontents line resolved my problem!
 
Upvote 0

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.

Forum statistics

Threads
1,214,649
Messages
6,120,728
Members
448,987
Latest member
marion_davis

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top