【问题标题】:Runtime Error 1004 Method Intersect' of object _Global failed对象 _Global 的运行时错误 1004 方法相交失败
【发布时间】:2019-03-02 08:40:25
【问题描述】:

我想加快一些数据输入。我在网上找到了有效的代码,直到我将相同的代码应用于更多的工作表。现在我明白了

运行时错误“1004”:对象“_Global”的方法“Intersect”失败

这是基本版本。它在不同的工作表上有所不同。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("D:D"), Target)
xOffsetColumn = 5
If Not WorkRng Is Nothing Then
    Application.EnableEvents = False
    For Each Rng In WorkRng
        If Not VBA.IsEmpty(Rng.Value) Then
            Rng.Offset(0, xOffsetColumn).Value = Now + 365
            Rng.Offset(0, xOffsetColumn).NumberFormat = "mm/dd/yyyy"
        Else
            Rng.Offset(0, xOffsetColumn).ClearContents
        End If
    Next
    Application.EnableEvents = True
Else
    Set WorkRng = Intersect(Application.ActiveSheet.Range("E:E"), Target)
    xOffsetColumn = 4
    If Not WorkRng Is Nothing Then
        Application.EnableEvents = False
        For Each Rng In WorkRng
            If Not VBA.IsEmpty(Rng.Value) Then
                Rng.Offset(0, xOffsetColumn).Value = Now + 365
                Rng.Offset(0, xOffsetColumn).NumberFormat = "mm/dd/yyyy"
            Else
                Rng.Offset(0, xOffsetColumn).ClearContents
            End If
        Next
        Application.EnableEvents = True
    End If
End If
End Sub

这似乎是问题所在:

Set WorkRng = Intersect(Application.ActiveSheet.Range("D:D"), Target)

【问题讨论】:

  • 我会使用 Me 而不是 Application.ActiveSheet tbh。
  • 您也可以使用DateAdd function 而不是在Now 中添加 365 天 - 闰年时不会导致错误。
  • 不要担心约会的事情。只是让代码在多个页面上工作是我的目标
  • 如果“指定了来自不同工作表的一个或多个范围”,Intersect 将失败。由于您使用的是 Worksheet_Change 事件,Target 应始终位于 ActiveSheet - 但是,Me 更可取。

标签: excel vba events excel-2007


【解决方案1】:

就我而言,我必须指定相交来自哪个应用程序:

Public Function IsInRange(Range1 As Range, Range2 As Range) As Boolean
    Dim Excel As Application, wb As Workbook, ws As Worksheet
    
    Set ws = Range1.Parent
    Set wb = ws.Parent
    Set Excel = wb.Application
    If Range1.Parent Is Range2.Parent Then
        IsInRange = Not (Excel.Intersect(Range1, Range2) Is Nothing)
    Else
        IsInRange = False
    End If
    Set ws = Nothing
    Set wb = Nothing
    Set Excel = Nothing
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多