首页 > 解决方案 > VBA 的 Worksheet_Change 函数使用 Intersect 方法与 Cells 作为范围定义器

问题描述

当相关单元格之一已更改时,我正在尝试使我的电子表格自动填充相应的单元格。我之前刚刚将目标定义为:

 If Target.Address = "$A$5" then

并且没有问题。但是,现在我的目标可以是许多单元格之一,并且我读到 intersect 方法应该能够为此工作,但是当我输入我的代码时:

If Intersect(Target, Range(Cells(12,2), Cells(12,j-1))) Is Nothing Then

(我正在尝试更改目标下方的单元格,目标是 12B 和 12(j-1) 之间的任何单元格,其中 j 是先前定义的)我收到以下错误:“运行时错误'1004':应用程序定义或对象定义的错误”但是据我所知,我的代码与周围的所有示例完全相同。

我的完整代码是(尽管我的 vlookup 也可能存在不相关的错误)

Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range(Cells(12, 2), Cells(12, j-1))) Is Nothing Then
    If IsEmpty(Target) Then
        Target.Interior.ColorIndex = 19
    Else:
        If Range("$A$13").Value = "" Then
            Range("$A$13").Value = "Care Type"
            Range("$A$13").Font.Bold = True
        End If
        Target.Interior.ColorIndex = xlNone
        Target.Offset(1, 0).Interior.ColorIndex = 19
        Target.Offset(2, 0).Value = Application.WorksheetFunction. _
            VLookup(Target, Sheets("Sheet2").Range("$E$3:$F$6"), 2)
        Target.Offset(2, 0).Font.Bold = True

        i = 2
        Do Until IsEmpty(Cells(11, i))
            If Cells(11, i).Value <= ChildCount Then
                Cells(12, i).Interior.ColorIndex = 19
            End If
        i = i + 1
        Loop
    End If
End If
End Sub

标签: vbaexcelintersect

解决方案


在使用 Intersect 确定您的范围内至少有一个单元格已更改后,您需要遍历匹配的单元格。

关闭事件处理,否则当您开始更改工作表上的值时,Worksheet_Change 将自行运行。

Private Sub Worksheet_Change(ByVal Target As Range)

    If not Intersect(Target, Range(Cells(12, 2), Cells(12, 11))) Is Nothing Then
        on error goto safe_exit
        application.enableevents = false
        dim t as range
        for each t in Intersect(Target, Range(Cells(12, 2), Cells(12, 11)))
            If IsEmpty(t) Then
                t.Interior.ColorIndex = 19
            Else
                If Range("$A$13").Value = "" Then
                    Range("$A$13").Value = "Care Type"
                    Range("$A$13").Font.Bold = True
                End If
                t.Interior.ColorIndex = xlNone
                t.Offset(1, 0).Interior.ColorIndex = 19
                t.Offset(2, 0).Value = Application.WorksheetFunction. _
                    VLookup(Target, Sheets("Sheet2").Range("$E$3:$F$6"), 2)
                t.Offset(2, 0).Font.Bold = True

                i = 2
                'I really don't know what the following code is intended to do
                'probably better as a conditional formatting rule
                Do Until IsEmpty(Cells(11, i))
                    If Cells(11, i).Value <= ChildCount Then
                        Cells(12, i).Interior.ColorIndex = 19
                    End If
                i = i + 1
                Loop
            End If
        next t
    End If

safe_exit:
    application.enableevents = true

End Sub

推荐阅读