Intersect命令因不同的工作表范围而失败

时间:2015-04-10 11:30:01

标签: excel vba excel-vba global intersect

我正在尝试创建自我更新下拉列表。为了实现这个目标,我找到了一个代码并将其改编为我的工作簿。如果代码名为"默认"但是当我尝试将其重定向到另一张纸时,它会卡在下面的代码中,出现此错误(方法'对象' _global失败"

如果相交(目标,工作表("默认")。范​​围(" c"& count_cells + 1))是什么都没有

    Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Dim count_cells As Integer
Dim new_value As String
Dim old_value As String
For count_cells = 1 To Worksheets("default").Range("c2:c400").CurrentRegion.Rows.Count - 1
    If Intersect(Target, Worksheets("default").Range("c" & count_cells + 1)) Is Nothing Then
    Else
        Application.EnableEvents = False
        new_value = Target.Value
        Application.Undo
        old_value = Target.Value
        Target.Value = new_value
        Range("AS:AS").Select
        Selection.Replace What:=old_value, Replacement:=new_value, LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
        Target.Select
    End If
Next count_cells
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:4)

如果两个范围在同一工作表上,则只能使用 Intersect()。例如:

Sub IntersectTest()
    Dim r1 As Range, r2 As Range, r3 As Range
    Set r1 = Sheets("Sheet1").Range("A1")
    Set r2 = Sheets("Sheet2").Range("A1")
    Set r3 = Intersect(r1, r2)
End Sub

会失败...........就像你的代码一样。