In this article, we will create a macro to copy data from a closed workbook.
We have “DataFile” containing employee data, which includes Name, Age and Domain.
We want to copy data from this file to the main file.
Before running the macro, we need to specify the file path and the file name.
Logic explanation
We have created “OpenClosedWorkbook” macro to copy data from the closed workbook. It opens the workbook, copies data to the main workbook and then closes the previous workbook.
Code explanation
Set WB = Workbooks.Open(FileName)
The above code is used to create an object of the opened workbook.
WB.Worksheets("Sheet1").Range("A1").CurrentRegion.Copy
The above code is used to copy all the data from the defined workbook.
ThisWorkbook.Worksheets("Main").Range("A15").PasteSpecial (xlPasteValues)
The above code is used to paste the copied data to the main worksheet.
Please follow below for the code
Option Explicit Sub OpenClosedWorkbook() 'Declaring variables Dim FileName As String Dim WB As Workbook 'Disabling screen updates Application.ScreenUpdating = False 'Getting file path and file name from the textbox FileName = Sheet1.TextBox1.Value 'Open the Excel workbook Set WB = Workbooks.Open(FileName) 'Copy data from sheet1 from opened workbook WB.Worksheets("Sheet1").Range("A1").CurrentRegion.Copy 'Paste data in the macro file starting from cell A15 ThisWorkbook.Worksheets("Main").Range("A15").PasteSpecial (xlPasteValues) 'Close the workbook without saving WB.Close (False) Set WB = Nothing 'Auto adjusting the size of selected columns Selection.Columns.AutoFit 'Saving the macro file ThisWorkbook.Save End Sub
If you liked this blog, share it with your friends on Facebook. Also, you can follow us on Twitter and Facebook.
We would love to hear from you, do let us know how we can improve our work and make it better for you. Write to us at info@exceltip.com
The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.
Thanks... Its what I was looking for... 🙂
But I am facing a small problem. I am using this code for extracting data from 1000+ small XL Files into a single XL file.
Filename of the small source XL files are datewise and hence I have used loop for this. Everything is working fine, except,
I get a message each time.
"There is large amount of information on Clipboard... "
How to get rid off this ... ?
Regards
John
Hi John,
You need to empty the clipboard in the end of the loop. put this line before "Next" of for.
Good information and i enjoyed it