我有一个工作簿,其中有两个工作表,分别是“每日目标”和“工作人员目标”。
如果我在“日常目标”工作表上工作,无论如何,我都需要允许我保存工作簿的代码。但是,如果我正在“工作人员目标”工作表上并且想要保存,则在条件满足时允许保存,否则不保存。
Option Explicit
'I wrote that code within "Staff Target" sheet.
Sub NotSave()
Dim WB As Workbook: Set WB = Workbooks("Target Sales Tmplate")
Dim ST As Worksheet: Set ST = Worksheets("Staff Targets")
With ST
If ST.Range("C" & Rows.Count).End(xlUp) <> Range("B4") Then
WB.Close SaveChanges:=False
MsgBox "Total Staff Target Amount is not equal to Total Monthly Target!", vbCritical, "ERROR"
End If
End With
End Sub
答案 0 :(得分:1)
将此代码放入ThisWorkbook
模块中:
Option Explicit
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim staffTargets As Worksheet
Set staffTargets = Worksheets("Staff Targets")
With staffTargets
If ActiveSheet.Name = .name Then
If .Range("C" & .Rows.Count).End(xlUp) <> .Range("B4") Then
MsgBox "Workbook Not Saved. Total Staff Target Amount is not equal to Total Monthly Target!", vbCritical, "ERROR"
Cancel = True
End If
End If
End With
End Sub