如果没有条目和显示消息框,则为Excel VBA,颜色必填字段(单元格)

时间:2012-11-23 12:32:39

标签: excel vba

我在Excel工作表上有一个表单,该表单有两个必需的单元格,这些单元格经常被用户不完整。我有以下代码,如果单元格未完成,将不允许用户保存工作表,将用红色突出显示它们并显示一个消息框:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

ok As Boolean
Dim xlSht As Worksheet
OK = False

Set xlSht = ThisWorkbook.Worksheets("Changes Form")

'Cell 1
If xlSht.Range("B13") = "" Then
    xlSht.Range("B13").Interior.Color = RGB(255, 0, 0)
    ok = True
Else
    xlSht.Range("B13").Interior.ColorIndex = xlNone
    ok = False

If xlSht.Range("E13") = "" Then
    xlSht.Range("E13").Interior.Color = RGB(255, 0, 0)
    ok = True
Else
    xlSht.Range("E13").Interior.ColorIndex = xlNone
    ok = False

End If

End If

If OK = True Then
MsgBox "Please review the highlighted cells and ensure the fields are populated."
Cancel = True
End If

End Sub

但是,如果两个单元格中都没有条目,则代码可以正常工作,那么它只会对单元格B13进行着色。我想一旦代码的'ok = True'位运行B13,它会跳过剩下的代码到最后。我不确定如何修改它以便突出显示两个单元格。

我考虑通过数据验证提醒用户,但是我在两个单元格中都有一个列表框,所以我不确定它是否仍然可以这样。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

使用以下代码替换您的代码。如果第一个值为空,那么您将错过第二个值的逻辑。此外,如果存在值,则无需设置为false。我改变的最后一件事是你对cellNotPopulated的“ok”布尔值,因此它更具可读性。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Dim xlSht As Worksheet
Dim cellsNotPopulated As Boolean
cellsNotPopulated = False

Set xlSht = ThisWorkbook.Worksheets("Changes Form")

    With xlSht

        If .Range("B13") = "" Then
            .Range("B13").Interior.Color = RGB(255, 0, 0)
            cellsNotPopulated = True
        Else
            .Range("B13").Interior.ColorIndex = xlNone
        End If

        If .Range("E13") = "" Then
            .Range("E13").Interior.Color = RGB(255, 0, 0)
            cellsNotPopulated = True
        Else
            .Range("E13").Interior.ColorIndex = xlNone
        End If

    End With

    If cellsNotPopulated = True Then
        MsgBox "Please review the highlighted cells and ensure the fields are populated."
        Cancel = True
    End If

End Sub