2

我正在尝试根据输入到单元格中的值自动启动宏。我能够为一个单元格做到这一点,但我怎样才能将它应用到一个范围,例如从 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 中输入一个值,如果条件满足等等......

4

2 回答 2

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
于 2013-11-05T22:41:00.373 回答
3

这是您正在尝试的(未测试)吗?

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

于 2013-11-05T22:37:34.953 回答