我在 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 运行,它会跳过其余代码到最后。我不确定如何修改它以便突出显示两个单元格。
我考虑过通过数据验证来提醒用户,但是我在两个单元格中都有一个列表框,所以我不确定这种方式是否仍然可行。
提前感谢您的帮助。