To open and close excel file using VBA Excel.
Here we are using a dialog box to open a excel file.We are opening only xlsx type of files here.
Sub OpenCloseExcelFile() Dim MyTargetFile As Variant 'First open a excel file MyTargetFile = Application.GetOpenFilename("Excel Files (*.xlsx), *xlsx") Workbooks.Open Filename:=MyTargetFile 'Give a name to the opened excel file, because it ensures that you are closing the correct file. MyOpenedFile = ActiveWorkbook.Name 'If needed we can add code to modify data or perform any operation on opened excel file 'As a general practice, we can save the workbook before we close Workbooks(MyOpenedFile).Save 'Close the workbook Workbooks(MyOpenedFile).Close End Sub
- You can use this approach when you have opened multiple files, then you can provide each of them a temporary name [e.g. MyOpenedFile], then close any file which you do not require.
- If needed,we can also add code for data manipulation in between,.
- Saving a file before closing is optional, it depends if you have modified the file or not.
Post you may like