【问题标题】:Excel VBA - Make multiple fields required based on value of another fieldExcel VBA - 根据另一个字段的值制作多个字段
【发布时间】:2013-04-17 23:57:34
【问题描述】:

我用 VB 在 Excel 中创建了一个请求表单,它使用提交按钮根据输入表单的值在 Outlook 中生成电子邮件。

一切正常。但是,用户通常无法在提交请求之前完成所有必要的字段。

我需要确保用户在提交请求之前在单元格 D7 中输入特定值时填写所有必填字段

这就是我迷路的地方...我尝试了两种略有不同的方法。

希望有人可以帮助我!

方法一:

当提交按钮被按下时...

Button_click()

If Range("D7").Value = "Special Request" THEN
'Make cells B6, B7, B8, B9, D14 mandatory in order to generate email 

    On Error Resume Next
    If ThisWorkbook.Worksheets("Request").Range _
    ("B6, B7, B8, B9, D14 ") Is Nothing Then

    MsgBox ("Please confirm all required fields have been completed!")

'Do not generate email

方法二:

当提交按钮被按下时...

Button_click()


'If the value of cell D7 is ANYTHING OTHER THAN "Special Feature", 
'execute code as normal to generate email

'Else, check for empty fields in the required cells ("B6, B7, B8, B9, D14 ") 

'if any required cells are empty, display message and do not generate email    
MsgBox ("Please confirm all required fields have been completed!")   

'If D7 = "Special Feature" AND NO REQUIRED FIELDS ARE MISSING, 
'continue with executing code to     generate email

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    这是一种解决方法:

        Sub test()
    If Range("D7").Value = "Special Request" And _
        Range("B6").Value = "" Or _
        Range("B7").Value = ""  Or _
        Range("B8").Value = "" Or _
        Range("B9").Value = "" Or _
        Range("D14").Value = "" Then
            MsgBox ("Please confirm all required fields have been completed!")
            Exit Sub
    Else
            ' whatever method you're using to generate email goes here
    
    End If
    
    
    
    End Sub
    

    这是使用 CountA 的另一种方式:

    Sub test2()
    
    If Range("D7").Value = "Special Request" And _ 
    Application.WorksheetFunction.CountA(Range("B6:B9"), Range("D14")) < 5 Then
            MsgBox ("Please confirm all required fields have been completed!")
            Exit Sub
    Else
            ' whatever method you're using to generate email goes here
    
    End If
    
    
    End Sub
    

    【讨论】:

    • 我认为那些应该是ORs 在#1 的范围之间。对于#2,不应该是&lt;5吗?
    • +1 表示数字 2,我认为这是要走的路。在 #1 上,我会再做一件事 - 在 ORs 周围加上括号。我不确定没有它们它是否会起作用,无论如何,他们会澄清条件。
    • 对于它的价值,在我的模型中,#1 没有任何括号。我也更喜欢#2,但我猜有选项很好。 #1有一些好处,例如,如果业务需求发生变化,您可以为每个字段指定各种条件,而无需进行大量返工,尽管如果您对大量必填字段过于疯狂,其中唯一的要求,则效率不高是“不能为空”。
    • 太棒了!使用第一种方法,它就像一个魅力。感谢所有的投入!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    相关资源
    最近更新 更多