使用VBA在Excel上自动更新上次更新

时间:2018-03-26 13:50:44

标签: excel vba excel-vba

  1. 我有一个我需要更新的Cell列表。例如:我需要更新单元格(“H 6:Q 11”)和H 13:Q 18和H 20:Q 25,依此类推。在每个单元格范围内,只要我更新其中一个单元格(例如H 7),我希望Cell D 6放置我最后更新的日期。如果我没有在H 13:Q 18上更新任何内容,我希望Cell D 13保持原样。这可以编码吗?

  2. 我尝试了类似下面的代码,但它没有用

  3. 代码

    Private Sub Worksheet_Change(ByVal Target As Range)
    
    Dim xCellColumn As Integer
    Dim xTimeColumn As Integer
    Dim xRow, xCol As Integer 
    
    xCellColumn = 2
    xTimeColumn = 1
    xRow = Target.Row
    xCol = Target.Column
    
    If Target.Text <> "" Then
        If xCol = xCellColumn Then
            Cells(xRow, xTimeColumn) = Now()
        End If
    End If
    
    End Sub
    

1 个答案:

答案 0 :(得分:0)

禁用事件并处理可能的多个目标单元格。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    'If Not Intersect(Target, Range("H6:Q11, H13:Q18, H20:Q25")) Is Nothing Then
    If Not Intersect(Target, Range("H:Q"), Range("6:1048576")) Is Nothing Then
        'Debug.Print Target.Address(0, 0)
        On Error GoTo safe_exit
        Application.EnableEvents = False
        Dim rng As Range
        For Each rng In Intersect(Target, Range("H:Q"), Range("6:1048576"))
            If (rng.Row Mod 7) <> 5 Then
                Cells(rng.Row, "D").Offset(((rng.Row Mod 7) <> 6) * ((rng.Row Mod 7) + 1), 0) = Now
            End If
        Next rng
    End If
safe_exit:
    Application.EnableEvents = True
End Sub