【问题标题】:How to have apply Worksheet_Change to more than one cell?如何将 Worksheet_Change 应用于多个单元格?
【发布时间】:2021-05-26 03:33:24
【问题描述】:

每当手动满足同一行中另一个单元格中的条件时,我实现了代码来为单元格添加时间戳:

Private Sub Worksheet_Change(ByVal target As Range)

    Dim A As Range: Set A = Range("A2:A2800")
    Dim v As String
    If Intersect(target, A) Is Nothing Then Exit Sub
    
    Application.EnableEvents = False
    v = target.Value
    If v = "" Then target.Offset(0, 6) = ""
    If v = "Solicitud enviada" Then target.Offset(0, 6) = Date
      
    Application.EnableEvents = True

End Sub

我需要用不同的标准为另一个单元格添加时间戳。我知道我不能同时拥有两个 Worksheet_Change 订阅者,但根据我的调查,试图同时拥有两个事件超出了我的范围。

Private Sub LeadTimeStamp(ByVal target As Range)

    Dim D As Range: Set D = Range("D2:D2800")
    Dim b As String
    If Intersect(target, D) Is Nothing Then Exit Sub

    Application.EnableEvents = False
    b = target.Value
    If b = "" Then target.Offset(0, 8) = ""
    If b = "lead" Then target.Offset(0, 8) = Date

    Application.EnableEvents = True

End Sub

b 需要作为字符串数组与单元格进行比较,如果是 JavaScript,则类似于 b.length <= 10
我知道VBA使用LEN(),但我不知道如何在这里使用它。现在我有一个类似于原始代码中的占位符条件,以确保代码在我处理数组条件部分之前有效。

【问题讨论】:

    标签: excel vba timestamp


    【解决方案1】:

    您的情况是您需要检查几个可能的更改之一,这意味着Target 级别的If 语句。所以在大纲形式中,它看起来像这样:

    Private Sub Worksheet_Change(ByVal Target As Range)
    
        '--- only deal with single-cell changes. multi-cell
        '    edits are skipped
        If Target.CountLarge > 1 Then Exit Sub
    
        Dim solicitudArea As Range
        Dim leadArea As Range
        Set solicitudArea = Range("A2:A2800")
        Set leadArea = Range("D2:D2800")
    
        Application.EnableEvents = False
        If Not Intersect(target, solicitudArea) Is Nothing Then
            '--- a request has changed
            If Target.Value = vbNullString Then 
                Target.Offset(0, 6).Value = vbNullString
            ElseIf Target.Value = "Solicitud enviada" Then 
                Target.Offset(0, 6).Value = Date()
            End If
        ElseIf Not Intersect(target, leadArea) Is Nothing Then
            '--- a request has changed
            If Target.Value = vbNullString Then 
                Target.Offset(0, 8).Value = vbNullString
            ElseIf Target.Value = "lead" Then 
                Target.Offset(0, 8).Value = Date()
            End If
        End If
        Application.EnableEvents = True
    End Sub
    

    一个好的做法是使用与这些值所代表的内容相匹配的变量名。它使代码在以后更易于阅读和维护。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2013-09-08
      • 2022-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多