在子程序中,我想打开一个工作簿,从中读取一些工作簿并关闭它 出于某种原因,我收到了一个错误:
Run-time error '1004':
Method 'Close' of object _Workbook failed
我已经确定了一个最小的代码片段来重现问题 创建一个新的Excel文件。在其中,创建一个Userform。在此,使用以下Click事件代码创建一个命令按钮:
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
让我感到困惑的是,当Command按钮不在用户窗体上时(在工作表上的普通按钮上),相同的代码不会发生此错误。
我甚至不知道还有什么要报告或在哪里寻找解释这种行为(除了StackOverflow!)。我正在使用Excel for Mac 2011编写VBA,如果它有所作为,可以转移到Windows Excel 2010。
答案 0 :(得分:7)
是的,在Excel 2011中,它是一个错误(未记录 - 我还没有找到它的文档)。您必须稍微修改代码。试试这个
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
答案 1 :(得分:0)
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