Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$D$10" Then
Call mymacro
End If
End Sub
问题是:
答案 0 :(得分:6)
您可以使用Workbook_SheetChange事件。将代码放在工作簿模块中。然后就不需要复制任何代码了。
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Address = "$D$10" Then
Call mymacro
End If
End Sub
编辑如果您需要阻止代码在某些工作表上运行,您可以添加以下功能
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
On Error Resume Next ' Invalid Parameters passed, IsInArray will be defaulted to FALSE
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
并将Workbook_SheetChange事件更改为
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim shArr() As Variant
'Example, mymacro will not run on the sheets "Overview" and "Total"
shArr = Array("Overview", "Total")
If Not IsInArray(Sh.Name, shArr) Then
If Target.Address = "$D$10" Then
Call mymacro
End If
End If
End Sub
答案 1 :(得分:1)
@davesexcel的一个示例改编,因为我之前从未尝试过这种方式。此代码位于标准模块中,您可以从主子调用。需要将引用添加到VBA Extensibility并访问要受信任的vb模型。
Public Sub AddWorksheetEventCode()
'Tools > references > Microsoft Visual Basic for Applications Extensibility 5.3
'Trust access to VBA model
Dim wb As Workbook
Dim wsNew As Worksheet
Set wb = ThisWorkbook
Dim xPro As VBIDE.VBProject
Dim xCom As VBIDE.VBComponent
Dim xMod As VBIDE.CodeModule
Dim xLine As Long
wb.Worksheets.Add After:= wb.Worksheets(ActiveSheet.Index)
Set wsNew = ActiveSheet
With wsNew
Set xPro = wb.VBProject
Set xCom = xPro.VBComponents(wsNew.Name)
Set xMod = xCom.CodeModule
With xMod
xLine = .CreateEventProc("Change", "Worksheet")
xLine = xLine + 1
.InsertLines xLine, "If Target.Address = ""$D$10"" Then "
xLine = xLine + 1
.InsertLines xLine, "Call mymacro"
End With
End With
End Sub
启用Trust access到VBA项目对象模型:
**阅读信任对vba项目模型的访问,以确定是否适合您。
答案 2 :(得分:0)
喜欢这个
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$D$10" Then
Call mymacro
Me.Copy after:=Sheets(Sheets.Count)
ActiveSheet.Cells.Clear
End If
End Sub
答案 3 :(得分:0)
我已经投了@Storax的答案,因为我不知道。但是,您应该记住,Workbook_SheetChange事件将触发所有表,可能包括您不希望运行宏的部分。因此,您需要添加代码以防止宏在您不想要的情况下触发事件时采取操作。
作为替代方案,请查看您创建工作表的方式。如果您insert
新的表单,新添加的内容将完全为空白,但如果您使用"移动或复制/创建副本" (或其等效的VBA)你得到一张新的工作表,它是原件的副本,包括其代码。另一个优点是您可以获得完全格式化的工作表,并且通常很容易清除在此过程中也复制的任何数据。