简体   繁体   English

启用宏的工作簿未运行

[英]Macro enabled workbook not running

I'm trying to ensure that for each row in my spreadsheet, if cell B or C is not populated (in the range), then a message box alerts the user - and doesn't allow it to be saved.我试图确保对于我的电子表格中的每一行,如果单元格 B 或 C 未填充(在范围内),则消息框会提醒用户 - 并且不允许保存它。

I have the workbook saved as a Macro enabled (XLSM) file - but the Workbook_BeforeSave doesn't appear to be triggering.我将工作簿保存为启用宏 (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

工作簿中宏的屏幕截图

Can anyone see where I may have gone wrong?谁能看到我哪里出错了? Macros are enabled for the workbook.为工作簿启用宏。

Thanks for any advice,感谢您的任何建议,

Mark标记

Somehow in your code, you have disabled the events, thus the Save event is not caught.在您的代码中,您以某种方式禁用了事件,因此未捕获Save事件。 Try the following:请尝试以下操作:

  • Press Ctrl + G , while you are selecting the Visual Basic Editor;在选择 Visual Basic 编辑器时按Ctrl + G
  • Write Application.EnableEvents = True on the Immediate window that shows up;在显示的立即窗口中写入Application.EnableEvents = True
  • Press Enter ;Enter ;

Now the events would be activated.现在事件将被激活。


As mentioned by Jeep, using error handling is a good idea in this case, thus the events are always enabled back if something "bad" happens during code execution:正如 Jeep 所提到的,在这种情况下使用错误处理是一个好主意,因此如果在代码执行过程中发生“坏事”,事件总是会被启用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM