如果某些单元格发生更改,则自动应用条件

时间:2018-04-06 15:14:09

标签: vba excel-vba excel

每当细胞范围发生变化时,我想自动填充一个细胞(“C2:C5”)。它不起作用......

Sub Worksheet_Change(ByVal Target As Range)

Dim Celula As String
Dim KeyCells As Range
Set KeyCells = Range("C2:C5")

    Application.EnableEvents = False
    Range("U2").ClearContents
    Application.EnableEvents = True

    If Not Application.Intersect(KeyCells, Target) Is Nothing Then

        On Error Resume Next
            Celula = Application.WorksheetFunction.Hlookup("2017-S1", Range("D11:AF11"), 1, True)
        On Error GoTo 0
            Range("U2") = Celula

    End If

End Sub

如果我只放这个(并手动运行)它可以工作:

Sub Teste()

    Dim Celula As String

    Application.EnableEvents = False
    Range("U2").ClearContents
    Application.EnableEvents = True

    On Error Resume Next
        Celula = Application.WorksheetFunction.Hlookup("2017-S1", Range("D11:AF11"), 1, True)
    On Error GoTo 0
        Range("U2") = Celula

End Sub

我做错了什么?

2 个答案:

答案 0 :(得分:0)

对您的代码进行以下更改可能就足够了

Option Explicit

Sub Worksheet_Change(ByVal Target As Range)

Dim Celula As String
Dim KeyCells As Range
Set KeyCells = Range("C2:C5")

    Application.EnableEvents = False
    Range("U2").ClearContents


    If Not Application.Intersect(KeyCells, Target) Is Nothing Then

        On Error Resume Next
            Celula = Application.WorksheetFunction.HLookup("2017-S1", Range("D11:AF11"), 1, True)
        On Error GoTo 0
            Range("U2") = Celula

    End If

    Application.EnableEvents = True

End Sub

更新:根据评论中的讨论,TO希望监控第二个工作表中的范围。如果发生更改,则应在另一个工作表中进行更改。我们假设第二个工作表名为 Dashboard ,然后将以下代码放入 Dashboard 的工作表模块中

Option Explicit

Sub Worksheet_Change(ByVal Target As Range)

Dim Celula As String
Dim KeyCells As Range
Set KeyCells = Range("D2:D5")
Dim ws As Worksheet

    Set ws = Worksheets("Userdata")


    Application.EnableEvents = False
    ws.Range("U2").ClearContents


    If Not Application.Intersect(KeyCells, Target) Is Nothing Then

        On Error Resume Next
            Celula = Application.WorksheetFunction.HLookup("2017-S1", ws.Range("D11:AF11"), 1, True)
        On Error GoTo 0
            ws.Range("U2") = Celula

    End If

    Application.EnableEvents = True

End Sub

这里的假设是应该进行更改的工作表的工作表名称是 Userdata ,而工作表 Dashboard 中要监视的范围是 D2 :D5 。请相应修改。

答案 1 :(得分:0)

Storax答案是绝对正确的。您的代码已执行,但对工作表的更改再次触发更改事件,并再次清除单元格...但这次不满足条件,因此它保持为空。