VBA,运行相同的宏进行多项选择

时间:2017-12-15 18:33:23

标签: excel vba excel-vba

如果值在与日期相同的相关行中发生更改,我想更新第一列(A)的日期。

我可以使用以下代码一次为一个单元格执行此操作。但是,当选择多个单元格时,宏将停止运行。你能帮助我升级下面的代码以便为多个单元格工作吗?

我发现代码可以满足我对预定义目标和范围的要求,但我希望它能够在代码中没有定义目标或选择范围的情况下工作。

Example

Dim oldValue As Variant

'Get the old selected cell value
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    oldValue = Target.Value
End Sub

'Update the date in first column when new value on selected cell
Private Sub Worksheet_Change(ByVal Target As Range)  
    If (Target.Count = 1) And Not (Target.Column = 1) And Not (Target.Value = oldValue) Then
        Cells(Target.Row, 1) = Date
    Else

    End If
End Sub

修改(来自评论)

如果更改了多个单元格,我希望能够更新相关日期。例如,将字母“x”复制到范围C6,C8:C9时,A6A8A9中的日期应该更改。但是,当将字母“a”复制到相同的单元格时,只有A6A9应该更改,因为C8在进行更改之前已经是“a”。

1 个答案:

答案 0 :(得分:1)

Dim dict As Object

'Get the old selected cell value
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Set dict = CreateObject("Scripting.Dictionary")
    For Each cell In UsedRange.Cells
        dict.Add cell.Address, cell.Value
    Next cell
End Sub

'Update the date in first column when new value on selected cell
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not (Target.Column = 1) Then
        For Each cell In Target.Cells
            If dict.exists(cell.Address) Then
                If dict(cell.Address) <> cell.Value Then
                    Application.EnableEvents = False
                    Cells(cell.Row, 1) = Date
                    Application.EnableEvents = True
                End If
            Else 'if the cell was not used before and this is a new row being filled
                Application.EnableEvents = False
                Cells(cell.Row, 1) = Date
                Application.EnableEvents = False
            End If
        Next cell
    End If
End Sub