首页 > 解决方案 > 如何设置更改时运行多个不同宏的多个范围?

问题描述

我的问题很简单,但由于某种原因,我不知道该怎么做。问题是我有 16 个不同的范围和 16 个不同的宏。

命名范围是:

它一直持续到GManHGVisH

我要运行的宏非常相似。问题是:每当我对GManAGVisA进行任何更改时,我都会运行宏AttResACpGrlA。到目前为止,代码中的一切都是正确的,但我想每个人都知道我的目标是什么。我想对此进行扩展:每当我对GManBGVisB进行更改时,它都应该运行宏AttResBCpGrlB

我目前的代码是:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("GManA,GVisA")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
    AttResA
    CpGrlA
End If
End Sub

我该如何扩展它?

标签: excelvbaexcel-formula

解决方案


我认为这真的取决于你的其他潜艇做什么。我会建议更改 Sub 以接收更改后的单元格。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Debug.Print "Target: " & Target.Address
    Set KeyCells = Intersect(Target, Range("GManA,GVisA"))
    If Not KeyCells Is Nothing Then
        AttResA KeyCells
        CpGrlA KeyCells
    Else
        Set KeyCells = Intersect(Target, Range("GManB,GVisB"))
        If Not KeyCells Is Nothing Then
            AttResB KeyCells
            CpGrlB KeyCells
        End If
    End If
    Set KeyCells = Nothing
End Sub

' Normal Module
Sub AttResA(ByRef Target As Range)
    Debug.Print "AttResA()", Target.Address
End Sub

Sub CpGrlA(ByRef Target As Range)
    Debug.Print "CpGrlA()", Target.Address
End Sub

Sub AttResB(ByRef Target As Range)
    Debug.Print "AttResB()", Target.Address
End Sub

Sub CpGrlA(ByRef Target As Range)
    Debug.Print "CpGrlB()", Target.Address
End Sub

推荐阅读