哪个VBA宏可以在填充单元格时给出日期,但在发生任何事件时都不会

问题描述 投票:1回答:2

我有一个excel文件,实际上是我定期更新的数据库。每次我进行更新时,我都希望过滤在特定日期输入的数据。

所以我在网上发现这个宏非常适合我的应用程序。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim C As Range, D As Range, Inte As Range, r As Range
    Set C = Range("C:C")
    Set Inte = Intersect(C, Target)
    If Inte Is Nothing Then Exit Sub
    Application.EnableEvents = False
        For Each r In Inte
            r.Offset(0, 1).Value = Date
        Next r
    Application.EnableEvents = True
End Sub

它给了我单元格D我修改单元格C的那一天的日期。问题是,如果我真的在单元格C中放置文本,我只想要显示日期。有时我只是插入一行,但是空的单元格C,宏将其视为事件。然后它给我在单元格D中的日期,但是我没有写任何东西。

我想这应该是一个非常简单的线,用If Not IsEmpty(C.Value) Then在宏中添加某个地方,但我无法将它放在正确的位置,因为它不起作用...

提前感谢您提供的任何帮助。祝大家周末愉快!

excel vba events
2个回答
0
投票

尝试

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim C As Range, D As Range, Inte As Range, r As Range
    Set C = Range("C:C")
    Set Inte = Intersect(C, Target)
    If Inte Is Nothing Then Exit Sub
    Application.EnableEvents = False
        For Each r In Inte
        If Not IsEmpty(r.Value) Then  ' line added
        r.Offset(0, 1).Value = Date
        Else
        r.Offset(0, 1).Value = ""
        End If
        Next r
    Application.EnableEvents = True
End Sub

0
投票

使用SpecialCells仅对非空单元格起作用

而且你不需要循环

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Inte As Range

    Set Inte = Intersect(Range("C:C"), Target)
    If Inte Is Nothing Then Exit Sub
    Application.EnableEvents = False
    Inte.SpecialCells(xlCellTypeConstants).Offset(0, 1).Value = Date
    Application.EnableEvents = True
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.