Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

vba - How can an Excel Add-In respond to events in any worksheet?

Our workbooks are server-generated SpreadsheetML, which cannot include any VBA code. Creating native Excel files or Excel 2007 XML files is also not an option, unfortunately.

So, I have an Excel Add-In (VBA, not XLL) that each of our users installs to add some extra UDFs, etc. that our workbooks need.

This works great, but now I need to have a macro that needs to execute every time the user changes the text in any cell, regardless what workbook they are actively using at the time.

So far, I've created a new Class module (SheetChangeHandler) in my Add-In, with the following code:

Option Explicit
Private WithEvents App As Application

Private Sub Class_Initialize()
    Set App = Application
End Sub

Private Sub App_SheetChange(ByVal Sh As Object, ByVal Source As Range)
    Debug.Print "Changed"
    On Error GoTo Finish
    App.EnableEvents = False
    DoWorkOnChangedStuff Sh, Source
Finish:
    App.EnableEvents = True
End Sub

In my Add-In, I've added a line to instantiate the new class:

Public MySheetHandler As New SheetChangeHandler

My understanding is that this should make Excel send the Add-In all SheetChange events for all open workbooks, without those workbooks needing to contain any macro code.

But it's not working... no Debug lines, and my DoWorkOnChangedStuff code isn't being called when I change a cell on any worksheet.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't use the New keyword in the dim statement. You're telling it to instantiate the class when it's needed, but then you never refer to it again, so it's never needed. Instead:

Public MySheetHandler As SheetChangeHandler

Sub Auto_Open
   Set MySheetHandler = New SheetChangeHandler
End Sub

That line in the Auto_Open (which runs at startup) will instantiate the class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...