【问题标题】:Type Error on Change Event更改事件的类型错误
【发布时间】:2016-08-04 22:03:43
【问题描述】:

我在使用 Excel VBA 脚本时遇到了一些问题。我正在尝试将其设置为在将数据输入第一列时形成时间戳的位置,但在删除第一个单元格时删除该行。

不断弹出错误 13,但我看不到类型不匹配的位置。我试过了:

  • 将单独的Range 类型变量定义为Target
  • 将 Target.Column 和 Target.Row 设置为单独的变量
  • 使用 For 循环
  • 使用 For Each 循环
  • 使用 With 循环

    所有这些都不断抛出错误 13。下面是我的代码,我们将不胜感激。

        Private Sub Worksheet_Change(ByVal Target As Range)
    
        Application.ScreenUpdating = False
    
        If Target.Column = 1 Then
            If Target.Column = 1 And Target.Value2 <> "" Then
                Cells(Target.Row, 3).Value = Format(Date, "ddd mmm d, yyyy")
                Cells(Target.Row, 4).Value = Format(Now, "hh:mm")
            ElseIf Target.Value2 = "" Then
                Target.EntireRow.Value = ""
            End If
    
        End If
    
        Application.ScreenUpdating = True
    
    End Sub
    
  • 【问题讨论】:

    • 关闭屏幕更新,直到您修复它,并一次执行一行代码,直到您查明它所在的行 - 然后报告回来,否则问题可能会很明显。您可以将 EntireRow 设置为 "" - 还是必须使用 ClearContents?
    • 不要忘记TargetRange,因此可能由多个单元格组成,这会为If Target.Value2 &lt;&gt; "" Then 之类的内容带来问题。您可能希望沿着For Each cell in Target 的行实现一个外循环...
    • @Ralph 谢谢你的评论。我设法让它与下面的答案一起使用,并使用您的评论进行多行删除。感谢您的帮助!

    标签: vba excel


    【解决方案1】:

    在通过 VBA 更改单元格之前禁用事件。

    Private Sub Worksheet_Change(ByVal Target As Range)
    
        Application.ScreenUpdating = False
    
        If Target.Column = 1 Then
            Application.EnableEvents = False
            If Target.Column = 1 And Target.Value2 <> "" Then
                Cells(Target.Row, 3).Value = Format(Date, "ddd mmm d, yyyy")
                Cells(Target.Row, 4).Value = Format(Now, "hh:mm")
            ElseIf Target.Value2 = "" Then
                Target.EntireRow.ClearContents
            End If
            Application.EnableEvents = True
        End If
    
        Application.ScreenUpdating = True
    
    End Sub
    

    【讨论】:

    • 这就像一个魅力!我猜随着事件的开启,它陷入了自引用循环。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 2016-07-09
    相关资源
    最近更新 更多