In a subroutine, I want to open a book, read it, and close it.
For some reason, I get an error:
Run-time error '1004': Method 'Close' of object _Workbook failed
I defined a minimal piece of code to reproduce the problem.
Create a new excel file. In it, create a Userform. In doing so, create a Command button with the following Click event code:
Private Sub CommandButton1_Click() Dim filename As String Dim opened_workbook As Workbook filename = Application.GetOpenFilename() ' User selects valid Excel file Set opened_workbook = Application.Workbooks.Open(filename) ' File operations would occur here opened_workbook.Close ' Exception thrown here MsgBox "If you got here, it worked!" Unload Me End Sub
What really puzzles me is that this error does not happen with the same code when the Command button is not on the user form (on a simple button right on the sheet).
I donβt even know what else to report or where to look for an explanation of this behavior (besides StackOverflow!). I am writing VBA using Excel for Mac 2011 and can upgrade to Windows Excel 2010 if that matters.
source share