excel - 调试发现错误 91 与 intersect(target, [range variable]).value

标签 excel vba

供引用 :
设备 - MacBook;我通常使用 Windows。我在兼容性方面没有任何问题。
操作系统-大苏尔 v11.5.2
Excel Ver.- 16.60
文件类型-xlsm
操作详情 :
当任何值输入到 C 列中的相应单元格时,我需要列范围 D4:D26 来输入日期戳。
问题 :
我有这个代码-

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim EntryDate As String
    Dim rngA As Range  'Declared variable
    
    Set rngA = Range("D:D") 'Set Declared variable
    
    
    If Intersect(Target, rngA).Value <> "" Then 'This line is displaying the runtime 91 code
    EntryDate = Format(Now, "dddd, mmm dd, yyyy")
    ActiveCell.Offset(0, 1).Select
    ActiveCell.Value = EntryDate 'When I comment this line out I get no runtime errors
    
    End If
End Sub
  • 当我在 C 列中输入值时,我的预期结果就会发生。 D 列确实输出了日期戳。但也会返回运行时错误 91。

  • 附加说明 :
    我去过这个平台内的多个论坛和许多相关问题。尝试使用新的工作簿和工作表;我还尝试为变量对象指定当前工作簿和工作表,但运行时 91 仍然在同一有问题的行返回。我做错了什么关于我的 Intersect 语法?是导致它的<>吗?

    最佳答案

    两个迫在眉睫的问题:

  • 你需要测试If Not Intersect(Target, rngA) Is Nothing第一的。即需要测试是否Target和 D 列相交,在您尝试使用 .Value 之前.
  • 您正在修改 Worksheet_Change 中的工作表事件处理程序,导致事件再次触发。通常使用 Application.EnableEvents = False避免这种情况。
  • Private Sub Worksheet_Change(ByVal Target As Range)
        Dim rng As Range
        Set rng = Intersect(Target, Me.Range("D:D"))
    
        If Not rng Is Nothing Then
             Dim entryDate As String
             entryDate = Format$(Now, "dddd, mmm dd, yyyy")
    
             OnError GoTo SafeExit
             Application.EnableEvents = False
    
             Dim cell As Range
             For Each cell In rng
                 If Not IsEmpty(cell) Then
                    cell.Offset(,1).Value = entryDate
                 End If
             Next
        End If
    
    SafeExit:
        Application.EnableEvents = True
    End Sub
    

    关于excel - 调试发现错误 91 与 intersect(target, [range variable]).value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71874981/

    相关文章:

    ms-access - MS Access 2010 VBA 多个 Else If 问题

    vba - 根据整个列的条件计算不同值的数量

    python - 麻烦使用 python 将 xlsx 文件复制到另一个文件

    excel - 如何为多个数据透视表选择数据透视过滤器中的最后一项?

    excel - 添加 ".Cells"如何解决运行时错误 13?

    excel - 自动填充命名范围 VBA

    Excel VBA - 根据值更改单元格颜色

    vba - 用于合并 Excel 中其他列中的信息匹配的行的单元格的宏

    arrays - VBA - 公共(public)数组错误 - 下标超出范围

    python - 分析标签集的最佳方法?