我是 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
最佳答案
cancel = true
在 sub 结束时取消退出过程,因此工作簿保持打开状态
尝试这个
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
关于VBA - 无法关闭excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47258736/