Excel VBA - 根据另一个字段的值创建所需的多个字段

时间:2013-04-17 23:57:35

标签: excel-vba vba excel

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

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

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

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

希望有人可以帮助我!

方法1:

按下提交按钮时......

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

方法2:

按下提交按钮时......

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

1 个答案:

答案 0 :(得分:2)

这是一种方法:

    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