VBA – 无法closuresExcel

我是新来的VBA,我有这个简单的代码,导致一些单元格是强制性的,并突出显示单元格,如果它们是空的时打开工作簿。 但是,我无法closures我所拥有的代码。 谁能告诉我为什么?

Private Sub Workbook_BeforeClose(Cancel As Boolean) If Cells(2, 6).Value = "" Then MsgBox "Cell F2 requires user input", vbInformation, "Please filled up the mandatory cells" ElseIf Cells(2, 9).Value = "" Then MsgBox "Cell I2 requires user input", vbInformation, "Please filled up the mandatory cells" ElseIf Cells(4, 4).Value = "" Then MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells" End If Cancel = True End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) If Cells(2, 6).Value = "" Then MsgBox "Cell F2 requires user input", vbInformation, "Please filled up the mandatory cells" ElseIf Cells(2, 9).Value = "" Then MsgBox "Cell I2 requires user input", vbInformation, "Please filled up the mandatory cells" ElseIf Cells(4, 4).Value = "" Then MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells" End If Cancel = True End Sub Private Sub Workbook_Open() If Cells(2, 6).Value = "" Then Range("F2").Interior.ColorIndex = 6 ElseIf Cells(2, 9).Value = "" Then Range("I2").Interior.ColorIndex = 6 ElseIf Cells(4, 4).Value = "" Then Range("D4").Interior.ColorIndex = 6 End If End Sub 

在子的末尾cancel = true取消退出过程,所以工作簿保持打开状态

尝试这个

 Option Explicit Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim aaa As Variant For Each aaa In Array("F2", "I2", "D4") If Range(aaa).Value = "" Then MsgBox "Cell " & aaa & " requires user input", vbInformation, "Please filled up the mandatory cells" Cancel = True Exit Sub End If Next aaa Cancel = False End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim aaa As Variant For Each aaa In Array("F2", "I2", "D4") If Range(aaa).Value = "" Then MsgBox "Cell " & aaa & " requires user input", vbInformation, "Please filled up the mandatory cells" Cancel = True Exit Sub End If Next aaa Cancel = False End Sub Private Sub Workbook_Open() Dim aaa As Variant For Each aaa In Array("F2", "I2", "D4") If Range(aaa).Value = "" Then Range(aaa).Interior.ColorIndex = 6 Next aaa End Sub