VBA 多个文本框验证控件

VBA Multiple Textboxes Validation control

亲爱的,

我正在准备一个简单的用户表单,让老师在 class 中输入每个学生的姓名和身高。有两个文本框(textbox_name 和 textbox_height)和一个“添加到记录”命令按钮。我试图进行一些验证控制以防止输入空字符串。我的验证控件是在文本框为空的情况下,当单击“添加到记录”按钮时,相应的空文本框变为粉红色;当两个文本框都为空时,两个文本框都应该变成粉红色,但是在我下面的代码中只有第一个文本框变成粉红色。你能告诉我为什么以及如何纠正它吗?谢谢

Private Sub Cmd_addtorecord_Click()

    If TextBox_Name = "" Then
    
        TextBox_Name.BackColor = rgbPink
        Exit Sub
    
    End If
    
    If TextBox_height = "" Then
    
        TextBox_height.BackColor = rgbPink
        Exit Sub
    
    End If

    '....

End sub

你可以这样做:

Private Sub Cmd_addtorecord_Click()
    'ensure required fields have content
    If FlagEmpty(Array(TextBox_Name, TextBox_height)) > 0 Then
        MsgBox "One or more required values are missing", vbExclamation
        Exit Sub
    End If
    
    '....

End Sub

'check required textboxes for content, and flag if empty
'  return number of empty textboxes
Function FlagEmpty(arrControls) As Long
    Dim i As Long, numEmpty As Long, clr As Long
    For i = LBound(arrControls) To UBound(arrControls)
        With arrControls(i)
            clr = IIf(Len(Trim(.Value)) > 0, vbWhite, rgbPink)
            .BackColor = clr
            If clr = rngpink Then numEmpty = numEmpty + 1
        End With
    Loop
    FlagEmpty = numEmpty
End Function

您将在到达第二个文本框之前退出子程序。将您的代码更改为如下内容:

Private Sub Cmd_addtorecord_Click()

    If TextBox_Name = ""  or TextBox_height = "" Then
        If TextBox_Name = "" Then
            TextBox_Name.BackColor = rgbPink
        End If
        If TextBox_height = "" Then
            TextBox_height.BackColor = rgbPink
        End If
        Exit Sub
    End If
    


    '....

End sub