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

时间:2019-05-21 11:53:12

标签: excel vba userform

我正在尝试检查用户是否已完成所有Text,ComboBoxes。目前它可以正常工作,但效果不佳,因为它会在每个未完成的框和每个已完成的框之后显示msgbox。

我尝试了下面的代码,并移动了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

请帮助改进代码,以使所有Text和ComboBox都未完成时变成红色,并调出一个表示需要完成的msgbox。

如果所有操作都已完成,它也不应该提供msgbox,这是当前操作。...

1 个答案:

答案 0 :(得分:0)

大概您想对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