我是VBA的新手,我有这个简单的代码,它会导致某些单元格成为必需单元,并在工作簿打开时突出显示单元格。但是,我无法用我的代码关闭我的Excel。谁能告诉我为什么?
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
答案 0 :(得分:4)
子末尾的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