【问题标题】:Method 'Close' of object _Workbook failed when using UserForm in Excel 2011在 Excel 2011 中使用 UserForm 时对象 _Workbook 的方法“关闭”失败
【发布时间】:2014-02-18 18:09:20
【问题描述】:

这两个帖子我已经看过了:

Closing a Userform with Unload Me doesn't work

Error when closing an opened workbook in VBA Userform

他们都建议当你想从表单代码中关闭一个文件时,你需要先卸载表单(使用卸载我)。但是,如果我卸载,我有一个被取消引用的全局数组。

看看我下面的代码(它在分配 global_int(0,0) 进行测试时崩溃)。除非删除数组,否则我无法卸载表单。这真的是解决这个问题的唯一方法吗?

创建一个新的 excel 文件。在其中创建一个用户表单。在此基础上,使用以下 Click 事件代码和全局声明创建一个命令按钮:

Private global_int(2, 10) As Integer

Private Sub CommandButton1_Click()
    global_int(0, 0) = 23

    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
    Unload Me
    opened_workbook.Close    ' Exception thrown here

    Dim test As Integer
    test = global_int(0, 0)

    MsgBox "If you got here, it worked!"

End Sub

我只是在调整别人的代码以在 Mac 上工作,所以我想尽可能避免完全重构。

谢谢。

【问题讨论】:

    标签: excel excel-2011 vba


    【解决方案1】:

    根据我的理解,您有一个 userForm,代码就在里面。您不能从 userForm 代码中卸载用户表单并期望其余代码正常工作。一种选择是在单独的模块中编写代码。调用用户表单从那里运行

    【讨论】:

    • 这或多或少是我最终做的。我使用了一个模块来声明所有全局变量,因此它们不在 userForm 的范围内。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    相关资源
    最近更新 更多