代码之家  ›  专栏  ›  技术社区  ›  4GetFullOf

ISNULL组合框

  •  0
  • 4GetFullOf  · 技术社区  · 6 年前

    我正在检查用户是否完成了表单中的所有字段。以下代码适用于所有字段,但我的多选组合框有问题。 现在,如果我将组合框留空,下面的代码将完美工作,并将bg颜色发送为红色。但是如果我选择的东西很好,那么我会在下面的一行得到一个不匹配的错误。如果是ull(ctrl)或len(ctrl)=0,那么

    Private Sub AddEmployee_Click()
        If CheckForEmpty = False Then
            MsgBox "Please fill in red boxes"
        Else
    
        End If
    End Sub
    
    Function CheckForEmpty() As Boolean
        CheckForEmpty = True
        ClearControlFormatting
    
        Dim ctrl As Control
        For Each ctrl In Me.Controls
            If ctrl.Tag = "FILL" Then
                If IsNull(ctrl) Or Len(ctrl) = 0 Then
                    ctrl.BackColor = vbRed
                    CheckForEmpty = False
                End If
            End If
        Next
    End Function
    
    Sub ClearControlFormatting()
        Dim ctrl As Control
        For Each ctrl In Me.Controls
            If ctrl.Tag = "FILL" Then
                ctrl.BackColor = vbWhite
            End If
        Next    
    End Sub
    
    Private Sub Form_Current()
        ClearControlFormatting    
    End Sub
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Erik A    6 年前

    多值组合框的值是一个数组,因此类型不匹配。

    使用 IsArray 要测试是否已设置:

    Function CheckForEmpty() As Boolean
        CheckForEmpty = True
        ClearControlFormatting
    
        Dim ctrl As Control
        For Each ctrl In Me.Controls
            If ctrl.Tag = "FILL" Then
                If Not IsArray(ctrl) Then
                    If IsNull(ctrl) OR Len(ctrl.Value) = 0 Then
                        ctrl.BackColor = vbRed
                        CheckForEmpty = False         
                    End If
                End If
            End If
        Next
    End Function
    
        2
  •  0
  •   Jericho Johnson    6 年前

    尝试以下操作:

    Dim ctrl As Control
    For Each ctrl In Me.Controls
        If ctrl.Tag = "FILL" Then
            If Len(ctrl.Value & "") = 0 Then
                ctrl.BackColor = vbRed
                CheckForEmpty = False
            End If
        End If
    Next ctrl
    

    连接零长度字符串时 "" 在VBA中,它将隐式地将该值转换为字符串,此时您可以安全地检查字符串的长度,以确定用户是否输入/选择了值。

    此类型的比较将保存验证中的一个步骤,并在尝试检查 Len() 为空值。 Len(Null) = Null 不是零,因此您当前的测试有可能出现运行时逻辑错误。

    如果控件在屏幕上是“空的”,根据它与字段的绑定方式,它可以作为零长度字符串或空值进行计算,从而在 Le() 测试。