Excel VBA,如果没有输入,则为必填字段(单元格)添加颜色,并显示消息框

Excel VBA,如果没有输入,则为必填字段(单元格)添加颜色,并显示消息框,excel,vba,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("Ch

我在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着色。我认为,一旦B13运行了代码中的“ok=True”位,它就会将其余代码跳过到最后。我不确定如何修改它,以便两个单元格都高亮显示

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


提前感谢您的帮助。

用以下代码替换您的代码。如果第一个值为空,则缺少第二个值的逻辑。此外,如果有值,则无需设置为false。最后一件事,我改变了你的“ok”布尔值为cellsNotPopulated,这样更可读

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