首页 文章

在Excel 2011中使用UserForm时,对象_Workbook的方法'Close'失败

提问于
浏览
1

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

Closing a Userform with Unload Me doesn't work

Error when closing an opened workbook in VBA Userform

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

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

创建一个新的Excel文件 . 在其中,创建一个Userform . 在此,使用以下Click事件代码和全局声明创建一个Command Button:

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上工作,所以我想尽可能避免完全重构 .

谢谢 .

1 回答

  • 0

    基于我能理解的是你有一个userForm并且代码在那里 . 您无法从userForm代码中卸载用户表单,并希望其余代码可以正常工作 . 一种选择是将代码写入单独的模块中 . 调用用户表单从那里运行

相关问题