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 = _
Workbooks(excelFile).Sheets(1).Range("A1").Value

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

1 comment:

  1. At work with excel files I recommend try good reliable tool to my mind-ms Excel sheet recovery tools,why it?,because program helped me in very difficult situation and has free status as far as I can see,utility can repair corrupted Microsoft Excel worksheets,restore data after problems with corrupted worksheet problem as a result of virus attack, disk and network failures or any other problem,an scan a damaged Microsoft Excel worksheet and repair it,work with *.xls, *.xlam, *.xltx, *.xlt and *.xlsm formats,recover modified Excel worksheets and shows recovered data in the same way, like it will be displayed in Microsoft Excel worksheet.

    ReplyDelete