Worksheet_SelectionChange 事件不一定必须驻留在特定于工作表的模块中。例如,它还可以驻留在 class module 中,并且对于本例来说很重要的是 ThisWorkbook 模块(尽管它被命名为 Workbook_SheetSelectionChangeevent)。
如果您总是想触发 Workbook_SheetSelectionChange 事件,无论
在选择更改的工作表中,尝试以下操作
'place in the ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
'Do stuff
MsgBox "Changes were made in worksheet: " & Sh.Name, vbInformation
End Sub
如果您只想在最新制作的 WS 上触发事件
1)您可以确保最新制作的 WS 始终是 WB 中的最后一个
'In a regular module
Sub addnwsheet()
Dim shtname As String
With ThisWorkbook
shtname = "temp" & .Sheets.Count
'add a sheet at the end
.Sheets.Add(after:=.Sheets(.Sheets.Count)).Name = shtname
End With
End Sub
'place in the ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If Sh.Index = ThisWorkbook.Sheets.Count Then
'Do stuff
MsgBox "Selection changed in worksheet: " & Sh.Name, vbInformation
End If
End Sub
2) 更安全的方法是将新制作的工作表声明为Global 变量。这些是持久的和公开的。
'In a regular module
Global nwsht As Sheet
Sub addnwsheet()
Dim shtname As String
With ThisWorkbook
shtname = "temp" & .Sheets.Count
'add a sheet at the end
.Sheets.Add(after:=.Sheets(.Sheets.Count)).Name = shtname
Set nwsht = .Sheets(shtname)
End With
End Sub
'place in the ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If Sh = nwsht Then
'Do stuff
MsgBox "Selection changed in worksheet: " & Sh.Name, vbInformation
End If
End Sub
编辑
如果你想指定事件应该触发的范围
'place in the ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Dim r as Range
Set r = Workbooks(REF).Sheets(REF).Range("D2:D100") 'event will only get triggered by this range
If Not Intersect(Target, r) Is Nothing Then
'Do stuff
MsgBox "Selection changed in worksheet: " & Sh.Name, vbInformation
End If
End Sub