【问题标题】:VBA Exit Sub in Userform without saving previously completed fields to sheet用户窗体中的 VBA 退出子而不将先前完成的字段保存到工作表
【发布时间】:2021-03-25 13:19:53
【问题描述】:

我在 Excel 中有一个基于 VBA 的用户窗体,我在应用一些逻辑时遇到了困难。 Userform 是用来收集数据的,并将其存储在 Excel 文件的工作表中。

在表单中,有四个单选按钮,在下面的注释“必须满足的四个条件”下。我希望在用户提交表单之前选择所有这四个按钮。代码的下半部分按预期运行良好,即用户必须选择所有四个选项,如果没有,则子退出并将它们发送回表单。

但是,问题在于每次将它们发送回表单时,表单中的其他值,例如代码上半部分的文本框保存到工作表中。

有什么方法可以退出,将用户发送回表单以正确完成,而不是将所有以前完成的字段保存到我的数据库表中?坚持了几个小时!

谢谢!

' Three demographic pieces of information
    .Cells(lRow, 8).Value = TextBox6.Value
    .Cells(lRow, 9).Value = TextBox7.Value
    .Cells(lRow, 10).Value = TextBox8.Value
    
' Four conditions which must be met
    If OptionButton4.Value = True And OptionButton5.Value = True And OptionButton6.Value = True And OptionButton7.Value = True Then
        .Cells(lRow, 11).Value = "Completed"
        .Cells(lRow, 12).Value = "Completed"
        .Cells(lRow, 13).Value = "Completed"
        .Cells(lRow, 14).Value = "Completed"
    ElseIf OptionButton4.Value <> True Or OptionButton5.Value <> True Or OptionButton6.Value <> True Or OptionButton7.Value <> True Then
         MsgBox "Please ensure the four condition boxes are checked"
         Exit Sub
    End If

【问题讨论】:

  • 将前三行移到if?
  • 我还要说,文件很大。数百个细胞。您认为这是可持续的良好做法吗?我可以看到这成为嵌套 if 的野兽。不过,我会试一试,好想,我没想到!我希望快速调整退出子功能!谢谢@Warcupine
  • 如果选项按钮未设置,请将前 3 个移入 if 或清除 ElseIf 中的单元格。
  • @NickAbbot 关于清除单元格的好主意。我喜欢。谢谢你——现在我听到了这些都是显而易见的想法。我想我太拘泥于细节了。我对将前 3 名移入 if 持谨慎态度,因为我可以看到有多个嵌套的 if。谢谢大家的支持!
  • 如果您担心可维护性,您可能希望开始避免使用神奇的数字,并为您的变量命名一些合理的名称。 (不同于TextBox6OptionButton5

标签: excel vba


【解决方案1】:

一个好的策略是将诸如“可以保存吗?”之类的决策抽象化。变成可重复使用的单独代码:

If OKToSave Then  'call your function

    ' Three demographic pieces of information
    .Cells(lRow, 8).Value = TextBox6.Value
    .Cells(lRow, 9).Value = TextBox7.Value
    .Cells(lRow, 10).Value = TextBox8.Value
    'other info...
    .Cells(lRow, 11).Value = "Completed"
    .Cells(lRow, 12).Value = "Completed"
    .Cells(lRow, 13).Value = "Completed"
    .Cells(lRow, 14).Value = "Completed"

Else
    MsgBox "Please ensure the four condition boxes are checked"
    Exit Sub
End If

你的“业务规则”是一个函数:

Function OKToSave() As Boolean
    OKToSave = OptionButton4.Value = True And OptionButton5.Value = True And _
               OptionButton6.Value = True And OptionButton7.Value = True
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-11-22
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多