Open a Closed Workbook with VBA in Microsoft Excel

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.

ArrowRawData

We want to copy data from this file to the main file.

ArrowMain

Before running the macro, we need to specify the file path and the file name.

ArrowOutput

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

Users are saying about us...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Terms and Conditions of use

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.

Visit Us On TwitterVisit Us On FacebookVisit Us On Google PlusVisit Us On Youtube