Introduction
In this post you can learn how to Open and Close a workbook using VBA in Microsoft Excel.
Objective:
A Macro which can open and close Excel workbook.
Solution:
Let's see a VBA code, which does it.
Simple Method:
Macro purpose: To open & close a excel workbook
Sub OpenRCloseWorkbook()
On Error Resume Next
Set wk = Workbooks.Open("C:\MyExcel.xlsx")
'Error Handling If file not found
If Err.Number = 1004 Then
MsgBox "File Not Found", vbCritical, "Warnings"
Err.Clear
Exit Sub
End If
ActiveWorkbook.Close
End Sub
On Error Resume Next
Set wk = Workbooks.Open("C:\MyExcel.xlsx")
'Error Handling If file not found
If Err.Number = 1004 Then
MsgBox "File Not Found", vbCritical, "Warnings"
Err.Clear
Exit Sub
End If
ActiveWorkbook.Close
End Sub
Tips :
If you want to close a workbook without the user being prompted about saving the workbook, use the below code
ActiveWorkbook.Close True 'SaveChanges:=TRUE
ActiveWorkbook.Close False 'SaveChanges:=FALSE
ActiveWorkbook.Close False 'SaveChanges:=FALSE
Dynamic Method:
This GetOpenFilename method displays the standard open Dialog box where user can select the file.
Sub OpenRCloseWorkbook()
Dim MyFile As String
MyFile = Application.GetOpenFilename()
Workbooks.Open MyFile
Filename = ActiveWorkbook.Name
Workbooks(Filename).Close True
End Sub
Dim MyFile As String
MyFile = Application.GetOpenFilename()
Workbooks.Open MyFile
Filename = ActiveWorkbook.Name
Workbooks(Filename).Close True
End Sub
!********************* Let me know how it works J ***************************!