更新时间:2023-12-05 19:13:16
这似乎是对实现的监督,应该根据设计实现此事件.实际上,Sheets
集合是Worksheets
和Charts
集合的并集.由于事件的名称为Workbook_SheetBeforeDelete
(而不是Workbook_WorksheetBeforeDelete
),因此常识表明该事件应适用于所有Sheets
,即Worksheets
和Charts
.
It's looks like an implementation oversight, this event should have been implemented according to the design. In fact, the Sheets
collection is the union of the Worksheets
and Charts
collections. Since the name of the event is Workbook_SheetBeforeDelete
(not Workbook_WorksheetBeforeDelete
), common sense dictates that the event should apply to all Sheets
, that is, both Worksheets
and Charts
.
请注意,图表和工作表都会引发其他事件,例如Workbook_SheetDeactivate
.这可以确认错误,但也可以通过利用Workbook_SheetDeactivate
事件来建议解决方法.
Notice that, other events such as Workbook_SheetDeactivate
are raised for both Charts and Worksheets. This confirms the error but also suggests a workaround by exploiting the Workbook_SheetDeactivate
event.
我们可以在ThisWorkbook
代码模块中添加两个过程. checkChartDelete()
检查图表是否已删除并启动适当的操作.它需要通过Application.OnTime
进行调用,因此它是通过静态变量chartNameToCheck
来获取其参数的.
We can add two procedures to ThisWorkbook
code module. checkChartDelete()
checks if a chart has been deleted and launches the appropriate action. It needs to be called through Application.OnTime
, so it gets its parameter through a static variable chartNameToCheck
.
' Code Module ThisWorkbook
Option Explicit
Private chartNameToCheck As String
Private Sub checkChartDelete()
On Error Resume Next
Dim x: Set x = Sheets(chartNameToCheck)
If Err.Number <> 0 Then
'**********************************************
' call or do here the action on chart deleted '
'**********************************************
MsgBox "chart deleted: " & chartNameToCheck
End If
chartNameToCheck = ""
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
If TypeName(Sh) <> "Chart" Then Exit Sub
chartNameToCheck = Sh.name
Application.OnTime Now, "ThisWorkbook.checkChartDelete"
End Sub