我试图根据输入到单元格中的值自动启动宏。我能够对一个单元执行此操作,但是如何将其应用于一个范围,例如从L1到L600?

以下是适用于1个单元格的代码:

Sub Worksheet_Change(ByVal Target As Range)

Dim CAD As String
CAD = "Canadians (CDN)"

    If Intersect(Target, Range("L14")) Is Nothing Then Exit Sub
    Application.EnableEvents = False 'to prevent endless loop

        If Range("L14").Value = CAD Then
        Range("M14") = 1
        End If

    Application.EnableEvents = True

End Sub


基本上,如果条件成立,我必须检查下一个单元格L15并在M15中输入一个值,依此类推...。

最佳答案

我看到Sid已经发布了答案,但这是一个稍微不同的版本:

Sub Worksheet_Change(ByVal Target As Range)

Dim CAD As String, c as Range, rng As Range
CAD = "Canadians (CDN)"

on error goto haveErr
    set rng = application.Intersect(Target, Me.Range("L1:L600"))
    if not rng is nothing then
        Application.EnableEvents = False
        for each c in rng.cells
           if c.value=CAD then c.offset(0,1).value=1
        next c
    End If

haveErr:
    Application.EnableEvents = True

End Sub

关于excel - 如何根据特定范围内不同单元格的值自动启动宏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19800290/

10-17 00:02