【问题标题】:Macro Hangs Second Time Showing a Userform when toggling between two userforms宏在两个用户表单之间切换时第二次挂起显示用户表单
【发布时间】:2021-03-06 16:24:38
【问题描述】:

我有两个用户表单。第一个表单有一个复选框,当检查时,它会导致表单消失(隐藏)和第二个表单出现。第二种形式提出一些问题,当它关闭(卸载)时,它会将答案写入位于第一种形式的代码中的字符串变量。 (以另一种形式写入另一个变量的部分不会影响我的问题,因为我已将其注释掉并且问题仍然存在。)

作为表单 2 的 userform_terminate 函数的一部分,它重新显示表单 1。

第一次按预期工作;复选框,表格1消失,表格2出现,关闭表格2,表格1出现。

在第二次尝试时,第二个表单将显示,但它的 userform_initialize 似乎没有触发(没有调试消息和断点未激活),并且宏停在包含在userform1 的代码(见下文)。

关闭按钮和右上角的 x 会在按下时动画,但没有任何反应。唯一的出路是重置代码。

第二条线索是 Userform2 中的第二条调试消息,Userform1.show 之后的一条没有打印出来。

第三条线索是在 Userform1 中 Userform2.show 之后立即设置的调试消息直到两个用户窗体都关闭(2 然后 1)才会出现。

由于Userform1.show,Userform2 似乎没有完全终止。

这里是代码sn-ps。

调用 Userform2 的 Userform1 子程序,它似乎停滞不前:

Private Sub InputCheckBox_Change()
    If InputCheckBox.Value = True Then
        Userform1.Hide
        Userform2.Show  'This is the line where it is stalled at if I break the execution
        debug.print "This message does not appear until after I've closed both"
    End If
End Sub

Userform2,这就是其中的一切:

Private Sub Userform2CloseButton_Click()
    Unload Userform2
End Sub
    
Private Sub UserForm_Initialize()
    Debug.Print "Userform2 initialized"
End Sub
    
Private Sub UserForm_Terminate()
    'Some stuff happens here but for testing I
    'commented it out and the issue is still there
    debug.print "This message will show up"
    Userform1.Show
    debug.print "But this message will not"
End Sub

我尝试了显示和隐藏顺序的各种组合,我认为这是this post中给出的答案。

作为一种解决方法,我可以改用 userform2.hide,它似乎可以工作。但它涉及额外的代码来处理使用右上角 x 而不是关闭按钮的情况。

【问题讨论】:

  • 仅供参考,为了避免歧义,您可以/应该在表单中使用Me 来引用表单本身。您正在使用表单的“默认实例”,如果可以的话,最好避免这种情况 - 参见例如 books.google.co.uk/…
  • @TimWilliams。感谢您花时间回复。我的实际代码没有使用 Userform1 和 Userform2,为了示例,我只是将它们更改为那个。我会听取您对使用Me more 的建议。

标签: excel vba userform


【解决方案1】:

所以我想我了解到的是,在显示 userform2 时暂停了 userform1 的执行,并在重新显示 userform1 时暂停了 userform2 的执行。因此,当 userform1 尝试重新显示 userform2 时,它无法加载,因为它从未完成卸载。

这是让我工作的代码。

用户表单1

Private Sub InputCheckBox_Change()
    If InputCheckBox.value = True Then
        Userform1.Hide
        Userform2.Show 'While Userform2 is being show, the code seems to halt here
        Userform1.Show 'Used to be in Userform2_Terminate or _QueryClose
    End If
End Sub

Userform2,再次完整

Private Sub DefineRepeatableCloseButton_Click()
    Unload DefineRepeatable
End Sub

Private Sub UserForm_Initialize()
    Debug.Print "DefineRepeatable initialized"
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    'Bunch of stuff happens here
End Sub

但是,我发现了将Userform1.show 放入 Userform2 的终止函数的代码示例,或者两个表单同时处于活动状态的示例。所以我确信我仍然对 VBA 表单有一些不理解的地方,所以如果有人有一个很好的参考资料可以解释其中的一些事情,我将不胜感激。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多