用于检查具有复杂条件的空组合框或文本框的VBA函数

时间:2015-10-21 16:53:32

标签: excel-vba combobox textbox vba excel

这是我第一次在这里提问,所以我希望我不会遗漏或忽略任何发布规则。

这是我的qustion:我有一个函数可以检查一系列输入框,在这种情况下是组合框和文本框,以查看用户是否已输入值。基本上它检查If (TextBox.value & "") = ""并在找到任何一个时返回False。

我想修改这段代码,如果我在Textbox1和Combobox1中有值,或者我在AAX和AAY中有值,则返回true。我只需要四个中的两个来进行计算。我尝试用And函数替换Or函数,但它似乎没有改变代码的功能。

提前感谢您的帮助!

功能代码:

Function validate() As Boolean

    Dim ret As Boolean

    If (TextBox1.Value & "") = "" Or (ComboBox1.Value & "") = "" Or (AAX.Value & "") = "" Or (AAY.Value & "") = "" Or (ComboBox2.Value & "") = "" _
        Or (ComboBox3.Value & "") = "" Or (RB.Value & "") = "" Or (MFC.Value & "") = "" Or (MCC.Value & "") = "" Or (LB.Value & "") = "" _
        Or (TB.Value & "") = "" Or (BB.Value & "") = "" Or (ComboBox4.Value & "") = "" _
        Then
            ret = False

        Else
            ret = True

    End If

    validate = ret

End Function

调用函数的代码:

Private Sub CommandButton1_Click()

    If Not validate() Then
       MsgBox "Fill all required fields, please"
       Cancel = True
    End If

End Sub

2 个答案:

答案 0 :(得分:0)

根据我的理解,如果任何两个项目都有值,你想要返回true。

基本上你需要If (item1 <> "" And item2 <> "") Or (item3 <>"" And item4 <> "") Then

您可以尝试这样的事情:

If (TextBox1.Value <> "" And ComboBox1.Value <> "") Or _
   (AAX.Value <> "" And AAY.Value <> "") Or _
   (ComboBox2.Value <> "" And ComboBox3.Value <> "") Or _ 
   (RB.Value <> "" And MFC.Value <> "") Or _
   (MCC.Value <> "" And LB.Value <> "") Or _  
   (TB.Value <> "" And BB.Value <> "") Then
        ret = False

    Else
        ret = True

End If

如果您想要返回true,如果 ANY 两个有值,则需要采用不同的方法。让我知道,如果是这样,我可以提供。

请注意,项.Value属性可能与其.Text属性不同。 What is the difference between .text, .value, and .value2?

答案 1 :(得分:0)

我根据你所写的内容做出了你想说的假设(伪代码):

  

如果(TextBox1和ComboBox1有值) OR (AAX和AAY有   值) AND 所有其余的框都有值然后返回   是的,否则返回False。

此代码将为您提供:

Function validate() As Boolean

    Dim ret As Boolean

    If (Len(TextBox1.Value) <> 0 And Len(ComboBox1.Value) <> 0) _
        Or (Len(AAX.Value) <> 0 And Len(AAY.Value) <> 0) _
        And Len(ComboBox2.Value) <> 0 And Len(ComboBox3.Value) <> 0 _
        And Len(RB.Value) <> 0 And Len(MFC.Value) = 0 _
        And Len(MCC.Value) <> 0 And Len(LB.Value) <> 0 _
        And Len(TB.Value) <> 0 And Len(BB.Value) <> 0 _
        And Len(ComboBox4.Value) <> 0 Then

        ret = True

    Else

        ret = False

    End If

    validate = ret

End Function