Excel 工作表中具有不同宏调用的多个目标\u更改VBA代码
我想使用工作表_change()来运行macro1(如果cell1被更改),macro2(如果cell2被更改),等等。我知道工作表_change()只允许target和sh,并且只能使用一个子表。我想我可以做一些类似的事情:Excel 工作表中具有不同宏调用的多个目标\u更改VBA代码,excel,syntax-error,worksheet-function,vba,Excel,Syntax Error,Worksheet Function,Vba,我想使用工作表_change()来运行macro1(如果cell1被更改),macro2(如果cell2被更改),等等。我知道工作表_change()只允许target和sh,并且只能使用一个子表。我想我可以做一些类似的事情: Private Sub Targets(ByVal Target As Range) Select Case Target.Address Case "cell1" Call SheetChange.macro1 Case "cell2" Call SheetChange
Private Sub Targets(ByVal Target As Range)
Select Case Target.Address
Case "cell1"
Call SheetChange.macro1
Case "cell2"
Call SheetChange.macro2
Case "cell3"
Call SheetChange.macro3
End Select
End Sub
但是,显然我不能!我也试过了
Private Sub Targets(ByVal Target As Range)
If Target.Address="cell1" Then
Call SheetChange.macro1
ElseIf Target.Address="cell2" Then
Call SheetChange.macro2
Elseif Target.Address="cell3" Then
Call SheetChange.macro3
End If
End Sub
但是那里也没有运气。有什么帮助吗?这里有一种方法:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" Then
MsgBox Target.Address
Exit Sub
End If
If Target.Address = "$A$2" Then
MsgBox Target.Address
Exit Sub
End If
If Target.Address = "$A$3" Then
MsgBox Target.Address
Exit Sub
End If
If Target.Address = "$A$4" Then
MsgBox Target.Address
Exit Sub
End If
End Sub
或者,如果您喜欢选择大小写语法,您可以选择以下方法:
Private Sub Worksheet_Change(ByVal Target As Range)
Select Case Target.Address
Case "$A$1"
MsgBox Target.Address
Case "$A$2"
MsgBox Target.Address
Case "$A$3"
MsgBox Target.Address
Case "$A$4"
MsgBox Target.Address
End Select
End Sub
看看这个例子。必须使用
Intersect
检查特定单元格是否已更改。我以A1
、A2
和A3
我还建议您看看这个,它告诉您在使用工作表\u Change
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
Application.EnableEvents = False
If Not Intersect(Target, Range("A1")) Is Nothing Then
'~~> Run Macro here
ElseIf Not Intersect(Target, Range("A2")) Is Nothing Then
'~~> Run Macro here
ElseIf Not Intersect(Target, Range("A3")) Is Nothing Then
'~~> Run Macro here
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
您可能还希望处理用户复制和粘贴多个单元格的情况。在这种情况下,使用此选项检查它并采取适当的行动
'~~> For Excel 2003
If Target.Count > 1 Then
End If
'~~> For Excel 2007 +
If Target.CountLarge > 1 Then
End If
不同的单元格在同一张纸上还是在不同的纸上?它们在同一张纸上确定1分钟。。。发布应答我可以用宏调用替换MsgBox Target.Address吗?可以,只需将消息框放在那里作为示例。没有任何东西可以阻止您将宏调用(或任何其他有效的VBA代码)放在那里。
应用程序+1。启用事件可避免堆栈溢出