0

我在 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 运行,它会跳过其余代码到最后。我不确定如何修改它以便突出显示两个单元格。

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

提前感谢您的帮助。

4

1 回答 1

1

用下面的代码替换你的代码。如果第一个值为空,那么您缺少第二个的逻辑。此外,如果有值,则无需设置为 false。我改变的最后一件事是你对 cellsNotPopulated 的“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
于 2012-11-23T13:12:20.043 回答