在不同的工作簿中捕获事件

时间:2023-01-06 19:13:58

I was wondering if it was possible to catch an event in another workbook.

我想知道是否有可能在另一个工作簿中捕获一个事件。

A macro will open a workbook for the user to use, and I want to be able to run another macro on its selection_change event. No, the code can't be stored in the just opened workbook.

一个宏将打开一个供用户使用的工作簿,我希望能够在其selection_change事件上运行另一个宏。不,代码无法存储在刚刚打开的工作簿中。

Is there any other way than programmatically adding a code to the opened workbook's ThisWorkbook module?

除了以编程方式将代码添加到打开的工作簿的ThisWorkbook模块之外,还有其他方法吗?

That way is unsafe and unstable and generally bleh.

这种方式是不安全和不稳定的,通常是无效的。

1 个解决方案

#1


1  

All you need to do it grab a WithEvents reference to the opened workbook in a class module with your event handlers. For example:

您只需要使用事件处理程序在类模块中获取对已打开工作簿的WithEvents引用。例如:

'In ThisWorkbook 
Option Explicit

Private WithEvents other As Worksheet

Private Sub Example()

    Dim wb As Workbook
    Set wb = Workbooks.Open("C:\Dev\other.xlsx")
    Set other = wb.Sheets("Sheet1")

End Sub

Private Sub other_SelectionChange(ByVal Target As Range)

    Debug.Print Target.Address

End Sub

#1


1  

All you need to do it grab a WithEvents reference to the opened workbook in a class module with your event handlers. For example:

您只需要使用事件处理程序在类模块中获取对已打开工作簿的WithEvents引用。例如:

'In ThisWorkbook 
Option Explicit

Private WithEvents other As Worksheet

Private Sub Example()

    Dim wb As Workbook
    Set wb = Workbooks.Open("C:\Dev\other.xlsx")
    Set other = wb.Sheets("Sheet1")

End Sub

Private Sub other_SelectionChange(ByVal Target As Range)

    Debug.Print Target.Address

End Sub