【发布时间】:2020-12-25 17:01:01
【问题描述】:
我正在使用 Workbook_BeforeSave 事件来检查是否在保存文档之前填写了所有必填单元格。如果有任何必填单元格为空,它将要求用户在保存文档之前填写它们。
代码按预期工作。但我面临的唯一问题是,当用户在未填写必填单元格的情况下单击 Close(X) 时,excel 会提示用户在关闭工作簿之前是否要保存/不保存更改或取消提示,如果用户点击保存,Workbook_BeforeSave 事件被调用,它通知用户有空的必填单元格需要填写并突然关闭文档。
我不想在用户单击“保存”时关闭工作簿,而必须填写必填单元格。如果他单击“不保存”,则关闭文档而不填写必填单元格。
如何做到这一点。
代码,
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim wb As Workbook
Dim ws1 As Worksheet
Dim userange, userange1, userange2 As Range
Dim iCell, positionrng As Range
Dim usedrow As Long
Dim usecolumn As Long
Dim rowposition As Long
Dim ws1lastrow, lastcol As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set wb = ThisWorkbook
Set ws1 = wb.Worksheets("CAPEX FY21-22")
rowposition = 9
criteria = ws1.Range("BM9").Value
investment = ws1.Range("BT9").Value
roi = ws1.Range("BU9").Value
justification = ws1.Range("BW9").Value
ws1lastrow = ws1.Cells(Rows.Count, criteria).End(xlUp).Row
If ws1.Cells(rowposition, criteria).Value = "" Or ws1.Cells(rowposition, criteria).Value = Empty Then
GoTo exiting:
End If
Set userange1 = ws1.Range(ws1.Cells(rowposition, criteria), ws1.Cells(ws1lastrow, investment))
Set userange2 = ws1.Range(ws1.Cells(rowposition, roi), ws1.Cells(ws1lastrow, justification))
Set userange = Union(userange1, userange2)
For Each iCell In userange
If IsEmpty(iCell) = True Then
MsgBox ("Document cannot be saved!" & vbCrLf & "Mandatory cell(s) are empty!" & vbCrLf & "Please fill the highlighted cell to save.")
iCell.Activate
ActiveCell.Interior.Color = RGB(255, 255, 0)
Application.Goto ActiveCell, Scroll:=True
Cancel = True
Exit Sub
GoTo exiting:
End If
Next
saves:
MsgBox ("Document saved")
exiting:
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
【问题讨论】:
标签: excel vba before-save