Excel VBA单击X时阻止保存工作簿

5ssjco0h  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(140)

我正在尝试创建宏,如果有单元格错误(如#VALUE!),则不允许工作簿用户保存工作簿。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
          Dim rng As Range
          Dim c As Range
          Dim a As Variant
          
          Set rng= ThisWorkbook.Sheets("Sheet1").Range("A1:C10")
          
          For Each c In rng
              If IsError(c.Value) Then
                  a = MsgBox(Prompt:="Check cells for #VALUE! and correct them before saving.", Title:="Check Cells")
                  Cancel = True
                  Exit For
              End If
          Next 
      End Sub

当用户单击“保存”按钮时,此操作运行良好,但当单击“X”然后单击“保存”时,我遇到了问题。发生此情况时,上面的宏仍会运行,但当用户单击消息框上的“确定”,告知他们无法保存时,关闭工作簿事件将继续,工作簿将关闭。这不是所需的行为。
我想要的行为(假设工作表有错误):
1.用户单击X和“保存”。工作簿有错误,因此不允许保存。工作簿保持打开状态
1.用户单击X,然后单击不保存。工作簿将正常关闭。

iq3niunx

iq3niunx1#

除了Workbook_BeforeSave事件之外,还应创建Workbook_BeforeClose事件。检查单元格是否有错误,如果需要,显示消息,然后取消关闭事件,以防止用户在更正错误之前退出。取消关闭事件后,不会出现要求保存工作簿的弹出窗口。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim rng As Range
    Dim c As Range
    Dim a As Variant
    
    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:C10")
    
    For Each c In rng
        If IsError(c.Value) Then
            a = MsgBox(Prompt:="Check cells for #VALUE! and correct them before saving.", Title:="Check Cells")
            Cancel = True
            Exit For
        End If
    Next
End Sub

如果您希望用户在工作簿有错误时仍然能够关闭,但不能保存。则显示YesNo消息框,并询问用户是否要关闭而不保存。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim rng As Range
    Dim c As Range
    Dim a As Variant
    
    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:C10")
    
    For Each c In rng
        If IsError(c.Value) Then
            a = MsgBox(Prompt:="Check cells for #VALUE! and correct them before saving.", Title:="Check Cells")
            If MsgBox("Close without saving?", vbYesNo) = vbYes Then
                Application.EnableEvents = False
                ThisWorkbook.Close SaveChanges:=False
                Application.EnableEvents = True
            Else
                Cancel = True
            End If
            Exit For
        End If
    Next
End Sub

相关问题