尝试在初始 'Cancel' 之后第二次启动或关闭红色 'X' 时出现 Excel 用户窗体运行时错误

标签 excel vba userform

问题:我正在构建一个具有“提交”和“取消”按钮的用户表单。如果用户点击“取消”按钮,我希望整个表单清除所有输入的数据并关闭表单,但如果用户点击右上角的红色“X”,我也试图构建相同的功能。我不清楚我需要在哪里卸载表格。我目前把它放在 btnCancel_Click()方法,我可以启动表单,输入一些数据并点击取消,它将关闭表单。

但是当我第二次尝试重新启动表单时,我收到一个错误(我附上了那条消息的图片),上面写着

"Run-Time error '-2177418105 (80010007): Automation Error - The Callee (server [not server application]) is not available and disappeared; all connections are invalid. The call may have executed.



如果我删除 Unload Me来自 btnCancel_Click()那么表单可以关闭并重新打开就好了,但是我第一次输入的任何数据仍然会在表单上并且没有被正确清除。我想知道这是否是 Unload Me错误还是在初始化表单时需要重置所有表单控件?
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
  ' how was the form closed?
  ' vbFormControlMenu = X in corner of title bar
  If CloseMode = vbFormControlMenu Then
    ' cancel normal X button behavior
    Cancel = True        
    ' run code for click of Cancel button
    btnCancel_Click
  End If
End Sub
'******************************************************************
Private Sub btnCancel_Click()
    mbCancel = True
    Me.Hide
    Unload Me

End Sub
'*********************************************************************
Private Sub UserForm_Initialize()
'Populate values for 2 combo boxes
lastEmp = Sheets("Form_Ref").Cells(Rows.Count, 1).End(xlUp).Row
Me.cmbBoxEmpName.List = Sheets("Form_Ref").Range("A2:A" & lastEmp).Value

lastBld = Sheets("Form_Ref").Cells(Rows.Count, 2).End(xlUp).Row
Me.cmbBoxBuildingName.List = Sheets("Form_Ref").Range("B2:B" & lastBld).Value

End Sub
'******************************************************************
Public form As New CheckOutForm
Sub testFormOptions()
'Button pressed within Excel will start program and show the userform
form.Show

End Sub

enter image description here

最佳答案

这是最简单又快又脏解决方案:

删除 Public form As New CheckOutForm从代码。然后添加到testFormOptions() :

Sub testFormOptions()
    Dim form As New CheckOutForm
    form.Show
End Sub

一些不太好的 VBA 书籍/教程甚至会有点像这样,但这是残酷的:
Sub testFormOptions()
    CheckOutForm.Show
End Sub

无论如何,现在表单中预定义值的问题已经解决。

对于干净而不简单的解决方案 ,考虑围绕表单编写一个MVC框架:
  • https://codereview.stackexchange.com/questions/154401/handling-dialog-closure-in-a-vba-user-form
  • this blogpost (免责声明 - 我的!),这几乎说明了上述链接的建议,但它没有问题中的错误。
  • the old StackOverflow tutorial for UserForms
  • 关于尝试在初始 'Cancel' 之后第二次启动或关闭红色 'X' 时出现 Excel 用户窗体运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537796/

    相关文章:

    VBA 重置所有复选框、组合框、文本框和数据验证下拉列表

    java - xlsx4j - 如何在电子表格中设置列宽?

    excel - VBA 图表集源数据

    excel - 从 Excel 中打开 Word 文档(Office 2016 和 MacOS)

    excel - vba 将控制称为变量语法

    excel - 停用 Excel VBA 用户窗体

    excel - 在范围内使用 LastRow

    c# - 通过 Web 服务将数据从 Sql Server 移动到 Excel

    sql - 如何在 Excel 工作表中的命名范围上运行 SQL 语句?

    vba - Excel VBA - 将用户窗体组合框的值分配给全局变量