触发将更新相同值的列中的单元格

时间:2018-09-26 23:08:28

标签: excel-vba for-loop triggers

我正在尝试编写一个宏,该宏将在我要完成的操作之前和之后更新与下面的相邻列具有相同值的列中的所有单元格。在此示例中,您将更新B1,然后A1中的任何具有相同值的单元格都会更新为B1值

Before

After

这是我正在使用的代码

Private Sub Worksheet_Change(ByVal Target As Range)

Dim rng1 As Range
Dim cel As Range

Set rng1 = Range("A1", Range("A2").End(xlDown))

For Each cel In rng1
    If cel = Target.Offset(0, -1).Value Then
    cel.Offset(0, 1).Value = Target.Value
    End If
Next cel

End Sub

我不确定我写的内容是否正确,但是我一直走出堆栈空间错误,我认为这是由于每次更改相同的单元格时,宏都会不断循环。我相信这应该可行,但我有点迷茫。

2 个答案:

答案 0 :(得分:0)

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column <> 2 Then Exit Sub

Application.ScreenUpdating = False
    For Each cel In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
        If cel = Target.Offset(, -1) Then
            cel.Offset(, 1) = Target
        End If
    Next cel
Application.ScreenUpdating = True

End Sub

答案 1 :(得分:0)

如果可能的话,我会尽量避免循环。也许使用.Find()方法来代替UDF?

Option Explicit

Function myLookup(ByVal rng As Range) As String

    Application.Volatile

    Dim ws As Worksheet, lookupRng As Range, retRng As Range
    Set ws = rng.Parent
    With ws
        Set lookupRng = .Range(.Cells(1, rng.Column), .Cells(rng.Row - 1, rng.Column))
    End With

    Set retRng = lookupRng.Find(rng.Value, ws.Cells(1, rng.Column))
    If retRng Is Nothing Then
        myLookup = vbNullString
    Else
        With retRng
            myLookup = ws.Cells(.Row, .Column + 1)
        End With
    End If

End Function

您可以将该UDF放置在工作表中,如下所示:

enter image description here

然后填写。这将防止循环引用,因为它将仅在lookupRng内搜索其上方的单元格

最终结果:

enter image description here