【问题标题】:Merging separate Double Click VBA events in a single worksheet在单个工作表中合并单独的双击 VBA 事件
【发布时间】:2022-06-11 18:44:49
【问题描述】:

我有一个电子表格,其中我调整了两段 VBA 代码来执行两个不同的双击事件操作。

第一段代码在双击时在特定范围的单元格中输入“✓”,再次双击时将其删除:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("H2:H600,M2:V600")) Is Nothing Then
    Application.EnableEvents = False
    If ActiveCell.Value = ChrW(&H2713) Then
        ActiveCell.ClearContents
    Else
        ActiveCell.Value = ChrW(&H2713)
    End If
    Cancel = True
End If
Application.EnableEvents = True
End Sub

第二段代码在双击时在一系列单元格中输入日期/时间戳:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Coded by SunnyKow - 16/09/2016
Application.EnableEvents = False
On Error GoTo ErrorRoutine
'You can change the range here
If Not Intersect(Target, Range("L2:L600,Y2:Y600")) Is Nothing Then
  'Update only if cell is empty
  If Target = "" Then
    Target = Now
  End If
  Cancel = True
End If
Application.EnableEvents = True
Exit Sub
ErrorRoutine:
Application.EnableEvents = True
End Sub

因为在单个工作表中不能有两个双击事件(作为单独的 VBA 代码),我如何合并这两个 VBA 片段,使其成为具有基于所选单元格范围的两个不同操作的单个代码片段。希望能提供任何帮助来解决此问题。

【问题讨论】:

    标签: excel


    【解决方案1】:

    看起来 if 语句可以解决问题

    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Application.EnableEvents = False
    On Error GoTo ErrorRoutine
    If Not Intersect(Target, Range("L2:L600,Y2:Y600")) Is Nothing Then
      'Update only if cell is empty
      If Target = "" Then
        Target = Now
      End If
      Cancel = True
    ElseIf  Not Intersect(Target, Range("H2:H600,M2:V600")) Is Nothing Then
        Application.EnableEvents = False
        If ActiveCell.Value = ChrW(&H2713) Then
            ActiveCell.ClearContents
        Else
            ActiveCell.Value = ChrW(&H2713)
        End If
        Cancel = True
    End If
    Application.EnableEvents = True
    Exit Sub
    ErrorRoutine:
    Application.EnableEvents = True
    End Sub
    

    【讨论】:

    • 嗨。感谢您的回复。我将 VBA 代码复制到我的工作表中,但它似乎不起作用。双击添加“✓”或双击添加日期/时间戳似乎都没有做任何事情。我知道我最初发布的各个 VBA 代码可以正常工作,但是它们的合并似乎不起作用。
    • 它确实有效,我录制了一个屏幕动画但我不知道如何在这里上传。
    猜你喜欢
    • 2012-03-30
    • 2018-01-06
    • 1970-01-01
    • 2012-01-25
    • 2013-10-06
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多