有没有办法修复代码以检查文本框或组合框是否为空?

Is there a way to fix the code to check if a textbox or combobox is empty?

我正在尝试检查用户是否已完成所有文本、组合框。目前它可以工作,但效果不佳,因为它会在每个未完成和每个已完成的框后弹出消息框。

我试过下面的代码,我已经移动了 MsgBox 的位置

Sub CheckEmpty()

Dim ctrlT As Object
Dim ctrlC As Object

For Each ctrlT In Me.Controls
If TypeName(ctrlT) = "TextBox" Then
    If ctrlT.Value = Empty Then
        ctrlT.BackColor = RGB(255, 0, 0)
    End If
End If
MsgBox "Please complete all missing information"
Next ctrlT

For Each ctrlC In Me.Controls
If TypeName(ctrlC) = "ComboBox" Then
    If ctrlC.Value = Empty Then
        ctrlC.BackColor = RGB(255, 0, 0)
    End If
End If
MsgBox "Please complete all missing information"
Next ctrlC

End Sub

请协助改进代码,使所有文本和组合框在未完成时变为红色,并显示一个消息框,提示需要完成。

如果所有都已完成,它也不应该给出一个消息框,它目前是这样....

大概你想对 CheckEmpty() 之后的数据做一些事情,这样调用代码需要知道测试的结果来决定它是否应该继续 - CheckEmpty() 可能应该是一个函数。

Sub Test()

    If (Not CheckEmpty()) Then
        '// come controls were empty
        Exit Sub
    End If

    MsgBox "do work"
End Sub

Function CheckEmpty() As Boolean

    Dim ctrl As Control
    Dim gotError As Boolean

    '// loop controls, all empty ones are red otherwise they are reset to white
    For Each ctrl In Me.Controls
        If TypeOf ctrl Is MSForms.ComboBox Or TypeOf ctrl Is MSForms.TextBox Then
            If ctrl.Value = Empty Then
                gotError = True
                ctrl.BackColor = RGB(255, 0, 0)
            Else
                ctrl.BackColor = vbWindowBackground
            End If
        End If
    Next ctrl

    If (gotError) Then MsgBox "Please complete all missing information"

    CheckEmpty = Not gotError
End Function