EXCEL VBA如何用一段代码控制多个工作表,而不用在每个工作表下写代码?

来源:百度知道 编辑:UC知道 时间:2024/09/24 08:36:27
我有一段代码,要在每个工作表中运行,现在我把这段代码写在每个工作表下面都有,这样十分不妥当,有没一种方法,就用一段代码,直接写在模块下,控制多个工作表?
Sub WorkSheet_SelectionChange(ByVal Target As Range)

If Target.Row > 0 Then
On Error Resume Next
[ChangColor_With].FormatConditions.Delete
'整行
Target.EntireRow.Name = "ChangColor_With"
'单元格
'Target.Name = "ChangColor_With"
With [ChangColor_With].FormatConditions
.Delete
.Add xlExpression, , "TRUE"
.Item(1).Interior.ColorIndex = 4 '绿色
End With
End If
End Sub

可以用一段就行了,如插入一个模块,给这段代码叫作abc
sub abc ()
你的一段代码
end sub

然后在每个工作表中画一个矩形,然后给这个按钮输入代码call abc

Sub 矩形1_单击()
Call abc
End Sub
----------------------------------------
那么你可以先插入一个模块,给这段代码叫作abc
sub abc ()
On Error Resume Next
[ChangColor_With].FormatConditions.Delete
'整行
Selection.EntireRow.Name = "ChangColor_With"
'单元格
'Target.Name = "ChangColor_With"
With [ChangColor_With].FormatConditions
.Delete
.Add xlExpression, , "TRUE"
.Item(1).Interior.ColorIndex = 4 '绿色
End With
end sub

然后你在每个工作表的WorkSheet_SelectionChange事件中输入
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Row > 0 Then
abc
End If
End Sub

注:有几个工作表就要在那几个工作表的SelectionChange中输入

If Target.Row > 0 Then
abc
End If

即可,你再运行一下试试看