如何根据特定范围内不同单元格的值自动启动宏

时间:2013-11-05 22:26:08

标签: excel vba events excel-vba

我正在尝试根据输入到单元格中的值自动启动宏。我能够为一个单元格执行此操作但是如何将其应用于范围,例如从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中输入一个值,等等......

2 个答案:

答案 0 :(得分:4)

我看到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

答案 1 :(得分:3)

这是你正在尝试的(UNTESTED)吗?

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim CAD As String: CAD = "Canadians (CDN)"

    If Target.Cells.CountLarge > 1 Then Exit Sub

    On Error GoTo Whoa

    Application.EnableEvents = False

    If Not Intersect(Target, Range("L1:L600")) Is Nothing Then
        If Target.Value = CAD Then Target.Offset(, 1).Value = 1
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

由于您使用的是Worksheet_Change,因此您可能也希望看到此POST