Friday, February 13, 2009

Excel VBA Macro Example: Opening & Closing a Workbook (Excel File)

When we're working on something using macro in excel, sometimes we need the data in a different excel file (workbook). Rather than open the file (workbook) manually, we can open excel file by using Excel VBA Macro. Following example will show you how to open & close the excel file using Excel VBA Macro.

Sub OpenCopyAndClose()
Dim excelFile As String

excelFile = "myfile.xls"

'open excel file "myfile.xls" in drive D:\
Workbooks.Open "D:\" & excelFile

'copy value of range A1 from "myfile.xls"
ThisWorkbook.Sheets(1).Range("D1").Value = _

'close "myfile.xls" file and don't save any changes
Workbooks(excelFile).Close SaveChanges:=False
End Sub