在Workbook_BeforeSave事件中调用sub

时间:2015-01-05 17:36:16

标签: excel excel-vba vba

我想在Workbook_BeforeSave事件中调用此Sub:

Sub test()
If ActiveSheet.Range("A4") = "" Then
MsgBox ("Please fill in cell A4!")
Exit Sub
Else
End If
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
 test
End Sub

单击保存时,即使单元格A4为空,也会保存文件。

3 个答案:

答案 0 :(得分:2)

您应将取消设置为终止保存事件的正确方法 将test作为函数会更好,因此您可以检查返回值,并相应地设置取消。

Function test() as Boolean
If ActiveSheet.Range("A4") = "" Then
    Test = False
Else
    Test = True
End If
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If test = False then Cancel=True
End Sub

此外,ActiveSheet不合适,除非您只有一个工作表,并且您已保护工作簿不添加额外的工作表。
我建议的解决方案是检查Sheets("MySheet").Range("A4")

当然,最懒的测试方法是:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
cancel = (ActiveSheet.Range("A4") = "")
End Sub

其中测试在保存过程中完成,不需要子测试。

答案 1 :(得分:0)

尝试:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Call test
End Sub

Sub test()
    If ActiveSheet.Range("A4") = "" Then
        MsgBox ("Please fill in cell A4!")
        End
    End If
End Sub

退出Sub 只会终止sub test(),而 End 会完全停止代码执行,从而阻止Workbook_BeforeSave()进一步运行。

答案 2 :(得分:0)

如果取消为真,则会阻止保存:

Sub Test(byref cancel as boolean)
    If ActiveSheet.Range("A4") = "" Then
        MsgBox ("Please fill in cell A4!")
        cancel = true
        Exit Sub
    'Else
    End If
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Test Cancel
End Sub