ChrisB
ChrisB

Reputation: 3225

Can I trigger the Workbook_SheetChange event from a different workbook?

I found an awesome script that checks if multiple worksheets are selected when a cell is changed and warns the user.

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
...

This prevents unintended changes if i have 10 worksheets selected and made a change on the visible worksheet.

I placed this script in the "ThisWorkbook" section of my "Personal" workbook. (This workbook automatically when Excel is open but is hidden). The problem is that it only triggers when a change is made to that "Personal" workbook so it's not checking to see what I am doing in any other workbook.

Is there anyway to trigger this action on any open workbook, without actually placing the script in that workbook? Also, if you found any questions in StackOverflow that cover this, please let me know. I couldn't find any. Thanks!

Upvotes: 1

Views: 910

Answers (2)

ZenZei
ZenZei

Reputation: 1

user6432984 gave the right answer. Full sample code in case you want to copy-paste:

Option Explicit

Private WithEvents ExcelApp As Excel.Application

Private Sub Workbook_Open()
    Set ExcelApp = Application
End Sub


Private Sub ExcelApp_SheetChange(ByVal Sh As Object, ByVal Target As Range)
   MsgBox "Cell changed"
End Sub


Private Sub ExcelApp_SheetPivotTableUpdate(ByVal Sh As Object, ByVal Target As PivotTable)
   MsgBox "PivotTable Updated"
End Sub

full event trigger list here (at the bottom)

For any event in the above link, click on the event type, and you will be able to see the parameters in C#. You'll have to change those parameters to VBA style as per my example above.

Upvotes: 0

user6432984
user6432984

Reputation:

Excel Application Events Reference

You can use WithEvents to trap the Excel.Application Events.


Private WithEvents ExcelApp As Excel.Application

Private Sub Workbook_Open()
    Set ExcelApp = Application
End Sub

enter image description here

Upvotes: 2

Related Questions