Error when closing an opened workbook in VBA Userform

后端 未结 2 1853
不知归路
不知归路 2020-12-11 06:15

In a subroutine, I want to open a workbook, do some reading from it, and close it.
For some reason, I get an error:

Run-time error \'1004\':

Method \'Cl         


        
相关标签:
2条回答
  • I had this exact problem on Excel 11 on Mac (Worked fine Excel 2013 on Windows), only the error occurred in a module sub that was called from the UserForm. If somebody (like me) is trying to use the workbook.close method from a sub/function in a module (or another location) that is not inside the UserForm itself you can't use 'Me'. 'Me' is only usable within the UserForm code itself.

    Instead of 'Unload Me' use the unload function and the name of your UserForm.

    Unload UserFormName
    
    0 讨论(0)
  • 2020-12-11 06:43

    Yes, in Excel 2011, it is a bug (Undocumented - I haven't found a documentation for it yet). You have to slightly modify the code. Try this

    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)
    
        Unload Me
    
        opened_workbook.Close    
    
        MsgBox "If you got here, it worked!"
    End Sub
    
    0 讨论(0)
提交回复
热议问题