excel 尝试在VBA代码中让特定单元格值触发多个宏

xe55xuns  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(267)

我正在Excel文档上创建输入页面。
单元格B3-可以有三个值,每个值触发不同的宏单元格B4-可以有两个值,每个值触发不同的宏
我写了下面的代码:

Sub worksheet_change(ByVal target As Excel.Range)
    If target.Cells.Count > 1 Then Exit Sub
    If IsNumeric(target) And target.Address = "$B$3" Then
        Select Case target.Value
        Case Is = 2: Class2
        Case Is = 3: Class3

        End Select
    End If
End Sub
Sub worksheet_change(ByVal target As Range)
Set target = Range("$B$4")
If target.Value = "yes" Then
 Call RetireeLife
End If
End Sub

然而,我发现worksheet_change在一个工作表中只能使用一次,但我不确定如何合并代码。任何帮助将不胜感激。

x33g5p2x

x33g5p2x1#

根据您要使用的ElseIf或Cases,下面演示了在worksheet_change中使用的这两个函数:

Sub worksheet_change(ByVal target As Excel.Range)
    If target.Cells.Count > 1 Then Exit Sub
    If IsNumeric(target) And target.Address = "$B$3" Then
        Select Case target.Value
        Case Is = 2: Class2
        Case Is = 3: Class3
        Case Is = 4: YourOtherSub 'You did say 3 options :p
        Case Else 
              MsgBox("Not a correct value in B3")
              Exit Sub            
        End Select
    ElseIf target.Address = "$B$4" Then
        If target.Value =  "yes" Then RetireeLife
        ElseIf target.Value = "no" Then KeepLiving 'or whatever your other macro is called
        Else
            MsgBox("Not a correct value in B4")
            Exit Sub
        End If          
    End If
End Sub

请注意,Exit Sub(除了第一个)是不必要的,因为无论何时到达代码中的这些行,您都将退出If并退出Sub。为了防止您追加额外的代码,它已经在那里了。如果您想使用Select来选择单元格,您可以使用Select来选择target.Address,然后检查"$B$3"的大小写是否为Numeric。
希望这有帮助!

相关问题