繁体   English   中英

将数据粘贴到其他列时自动将日期输入单元格

[英]Automatically enter date into cell when data is PASTED into other column

我试图找到一个 VBA 代码,当数据被复制并粘贴到同一行的 CL 列时,它会自动在 A 列中输入当前日期。

我想出了如何在手动将数据写入 C 列时自动输入日期,但是当我将数据粘贴到以下位置时,这将不起作用

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("C:C")) Is Nothing Then
With Target(1, -1)
.Value = Date
.EntireColumn.AutoFit
End With
End If

End Sub    

当我将数据输入到 C 以外的其他列(例如 DL)时,我还希望日期自动出现。

谢谢你们!

您可以这样做 - 只需更新正在检查的范围:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, rw As Range
    
    Set rng = Application.Intersect(Target, Me.Range("C:L"))
    
    'any tracked cells in Target range?
    If Not rng Is Nothing Then 
        Set rng = rng.Entirerow    
        For Each rw In rng.Rows   'loop updated rows
            rw.Cells(1) = Date    'put date in ColA
        Next rw
    End If
End Sub

如果它是您寻求的 VBA 解决方案,那么您可以在 Private Sub 中指定整个范围 C:L。 以下代码假设您只想填充 A 列中从 A2 开始的空白单元格:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim LastRow as Long
If Not Intersect(Range("C:L"), Target) Is Nothing Then

LastRow = Range("C:L").SpecialCells(xlCellTypeLastCell).Row
Range("A2:A" & LastRow).SpecialCells(xlCellTypeBlanks).Value = Date

End If
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM