添加新参考时,excel会停止触发事件

时间:2017-11-27 11:09:09

标签: excel vba excel-vba

我在 ThisWorkbook

中有此代码
Public WithEvents App As Application

Private Sub Workbook_Open()
   Application.EnableEvents = True
   ' it is a simple control RefEdit, but it could be anything:
   ThisWorkbook.VBProject.References.AddFromGuid{00024517-0000-0000-C000-000000000046},0,0 
   Set App = Application
End Sub

Private Sub App_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
   Debug.Print "Selection changed"
End Sub

此代码在Workbook open事件中添加了新的Reference。当执行从GUID添加引用的行时,excel将停止触发SheetSelectionChange个事件。以及其他事件。如果我评论该行,excel会成功触发所有事件。你能告诉我我做错了什么吗?是调用函数在项目中添加新引用的好地方吗?

1 个答案:

答案 0 :(得分:1)

显然,事件和添加新引用并不相爱 - reference

这是围绕它的方式,在那里提出:

Private Sub Workbook_Open()

'    'Must have reference to the VBE IDE to access reference information
'    ' Hardcode adding the GUID for the VBE IDE...
    ThisWorkbook.VBProject.References.AddFromguid "{00-000000000046}", 0, 0

    Application.OnTime Now() + TimeValue("00:00:01"), "SetupApplicationEvents"

End Sub

在一个模块中:

Sub SetupApplicationEvents
    Set App = Application
End Sub