宏启用的工作簿未运行

时间:2018-02-23 11:26:35

标签: excel vba excel-vba

我正在尝试确保对于电子表格中的每一行,如果未填充单元格B或C(在范围内),则会在消息框中提醒用户 - 并且不允许保存它。 / p>

我将工作簿保存为启用宏的(XLSM)文件 - 但Workbook_BeforeSave似乎没有触发。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim rng1 As Range
Dim rng2 As Range
MsgBox "hi"
Set rng1 = ActiveSheet.Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(3, 4)).Select
Stop

'turn off events to avoid code retriggering itself
Application.EnableEvents = False
For Each rng2 In rng1
    If Cells(rng2.Row, "B") = vbNullString Then
       MsgBox "Please Enter Something in Cell B - your entry will be deleted", vbOKOnly
       rng2.Value = vbNullString
    End If
    If Cells(rng2.Row, "C") = vbNullString Then
       MsgBox "Please Enter Something in Cell C - your entry will be deleted", vbOKOnly
       rng2.Value = vbNullString
    End If

Next
Application.EnableEvents = True
End Sub

Screenshot of macro in workbook

谁能看到我可能出错的地方?已为工作簿启用宏。

感谢您的任何建议,

标记

1 个答案:

答案 0 :(得分:1)

在您的代码中,您已禁用事件,因此未捕获Save事件。请尝试以下方法:

  • 在选择Visual Basic编辑器时,按 Ctrl + G ;
  • 在显示的Immediate window上写下Application.EnableEvents = True;
  • Enter ;

现在活动将被激活。

正如吉普所提到的,在这种情况下使用错误处理是一个好主意,因此如果出现“#34; bad"在代码执行期间发生:

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

    On Error GoTo Workbook_BeforeSave_Error

    'code here        

    On Error GoTo 0
    Exit Sub

Workbook_BeforeSave_Error:
    Application.EnableEvents = True
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in Workbook_BeforeSave"
End Sub