【发布时间】:2018-02-22 04:39:22
【问题描述】:
使用 Excel 2007,我知道我可以在它创建的工作表上创建 worksheet_change 事件。
但是如何将全局子更改事件分配给新创建的工作表?
例如
Public Sub DataChange(ByVal Target As Range)
' this will check and see if the user or operator has change the column field
' if they fill in "X", mark the whole row to red color
' otherwise leave it black
Dim KeyCells As Range
Dim LastRow As Long
LastRow = Cells(Rows.Count, 1).END(xlUp).Row
Set KeyCells = Range("L2:L" & LastRow)
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
If Target.Value = "X" Or Target.Value = "x" Then
Target.EntireRow.Font.color = vbRed
Else
Target.EntireRow.Font.color = vbBlack
End If
End If
End Sub
然后在Module1中的一个单独的子过程中...
Public Sub CreateWorkSheet()
Dim ws As Worksheet
Set ws = Sheets.Add
ws.Name = "Test1"
' Here where I want to set the event but I do not know the syntax
' ws.OnChange = DataChange
Debug.Print "Done"
End Sub
我习惯于在创建控件 (C#/WPF/Pascal) 时动态分配事件,所以我认为 Excel 世界中会有一个。任何建议或帮助将不胜感激。
【问题讨论】:
-
如果您创建一个空白工作表,将代码添加到工作表的代码表并将其隐藏,您可以复制它或将其用作未来新工作表的模板,代码将随之而来。或者,您可以选择 Workbook_SheetChange 事件处理程序。
-
问题,Excel 如何知道运行宏的工作表?我认为它仅限于它所关注的选定工作表?在这种情况下,更新单元格的代码被隐藏了,但是代码如何继续在另一个工作表上运行?听起来像是在 Excel 中发生的覆盖功能?另外这个问题是我可能只想在某些工作表上使用 sub 而不是全部。
-
A Worksheet_Change 只有 Target 传递给它; Workbook_SheetChange 具有 Sh 用于工作表和目标。我喜欢使用 Select Case 来解析工作表名称。
-
...是的,您的 DataChange 将需要对所有范围和单元格调用进行适当的父工作表引用,但是,这些应该从一开始就存在。