【问题标题】:VBA - Go back to Userform after msgboxVBA - 在 msgbox 之后返回用户窗体
【发布时间】:2022-01-19 21:20:55
【问题描述】:

我有一个用户窗体,其中当前有 15 个组合框。允许用户选择本季度、上季度和去年的 5 个报告。由于有很多可供选择的框,我认为最好应用一些错误处理以避免遗漏任何框。

我的代码是这样的(显然每个盒子都重复了):

If IsNull(UF_RM_Reports.Report1.Value) Then

MsgBoxResult = MsgBox("No report selected for Report 1 current quarter, is this correct?", vbYesNo + vbQuestion, "Report Template")

    If MsgBoxResult = vbNo Then
        End

    Else

    End If

End If

我遇到的问题是,如果用户意识到他们没有选择报告并按否,我已经结束,这不仅会结束宏,还会关闭组合框。如果您然后重新打开它,所有选择都消失了。有点挫败错误处理的意义,因为他们需要重新开始。

我想知道是否有什么可以更改 End 的内容,以停止代码但允许用户返回并选择丢失的报告。

提前致谢

【问题讨论】:

  • 您想退出子,这会将过程返回到表单。
  • 组合框是否命名为 Report1、Report2 等到 Report15 ?如果是这样,您不需要 15 块代码。您可以遍历它们并构建一条消息。

标签: excel vba userform


【解决方案1】:

有几种方法可以处理这种情况。由于我不知道您的 UserForm 的详细信息,我将概述一般方法。我倾向于在按下用户窗体上的按钮时验证控件,这表明用户已准备好生成报告:

Private Sub CommandButton1_Click()
   If Trim(Report1.Value) = "" Then
      If MsgBox("No report selected for Report 1...", vbYesNo + vbQuestion, "Report Template") = vbNo Then
         Report1.SetFocus
         Exit Sub
      End If
   End If

   If Trim(Report2.Value) = "" Then
      If MsgBox("No report selected for Report 2...", vbYesNo + vbQuestion, "Report Template") = vbNo Then
         Report2.SetFocus
         Exit Sub
      End If
   End If

   'create the reports when nothing has been missed or
   'the user wants to proceed anyway
   MsgBox "create reports"
End Sub

因为有很多控件,你可以用循环来完成同样的事情:

Private Sub CommandButton1_Click()
   Dim c As Control
   
   For Each c In Me.Controls
      If TypeOf c Is ComboBox Then
         If Trim(c.Value) = "" Then
            If MsgBox("You have not selected all reports.  Is this correct?", vbYesNo + vbQuestion, "Report Template") = vbNo Then
               Report1.SetFocus
               Exit Sub
            Else
               Exit For
            End If
         End If
      End If
   Next
   
   'create the reports when nothing has been missed or
   'the user wants to proceed anyway
   MsgBox "create reports"
End Sub

【讨论】:

    【解决方案2】:

    如果要求是让用户注意到他/她错过了报告选择这一事实,为什么不在任何一个事件中尝试摆弄组合框的颜色属性——比如?

    1. 在useform激活事件中设置组合框的颜色状态

      Private Sub UserForm_Activate()
      
        ComboBox1.BackColor = vbRed
        UserForm1.ComboBox1.AddItem "A"
        UserForm1.ComboBox1.AddItem "B"
        UserForm1.ComboBox1.AddItem "C"
      
      End Sub
      
    2. 然后在组合框更改事件中将颜色改回原来的颜色

      Private Sub ComboBox1_Change()
           If ComboBox1.value = "" Then
              ComboBox1.BackColor = vbRed
           Else
             ComboBox1.BackColor = &H80000005
           End If
      End Sub
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多