How to copy and paste data using a Macro in Excel. I'll show you multiple ways to do this, including across worksheets and workbooks.
Range("A1").Copy Range("B1")
This copies cell A1 to cell B1.
Range("A1").Copy is the part that copies the cell.
Range("B1") is the cell where the data will be copied.
This is a simple one line piece of code and it's very easy to use.
Notice that there is a space between these two parts of the code.
Range("A1:A5").Copy Range("B1:B5")
Range("A1:A5").Copy is the part that copies the range.
Range("B1:B5") is the range where the data will be copied.
You can also write it like this:
Range("A1:A5").Copy Range("B1")
Notice that the range to where you will copy the data has only a reference to cell B1.
You only have to reference the very first cell to which the range will be copied and the entire range will copy in the cells below there.
NOTE: if you do it like this, you may end up overwriting data and Excel will not give you a warning about this; the data will simply be filled down as far as it needs to go to copy the first range.
Sheets("Sheet1").Range("A1").Copy Sheets("Sheet2").Range("B1")
This follows the same pattern as the above examples except that we need to tell the macro from which sheet we want to get the data and to which sheet we want to copy the data.
Sheets("Sheet1"). is placed in front of the first range and that means to get the data from Sheet1, which is the name of a worksheet in the workbook.
Sheets("Sheet2"). is placed in front of the range to which we want to copy the data and Sheet2 is the name of the worksheet where the data will be copied.
Workbooks("Copy and Paste Data using Macro VBA in Excel.xlsm").Sheets("Sheet1").Range("A1").Copy Workbooks("Copy and Paste Data using Macro VBA in Excel.xlsm").Sheets("Sheet3").Range("A1")
Here, we follow the above examples and, this time, add a reference to the workbooks from which we want to get the data and to which we want to place the data.
Workbooks("Copy and Paste Data using Macro VBA in Excel.xlsm"). is the code that says in which workbook we want to place the data. Copy and Paste Data using Macro VBA in Excel.xlsm is the name of the workbook. In this example I used this for both parts, the workbook from which the data comes and where it goes. This allows you to run this macro within a single workbook and still show you how it works. In a real-world example, the first part contains the name of the workbook where you get the data from and the second contains the name of the workbook where you want to place the data.
Read this tutorial to copy values from another workbook, even if it's closed.
All examples in the attached workbook have been commented out. Simply remove the single quote from the line of code you want to test and then run the macro.
Download the attached file to get these examples in Excel.