运行时错误 50290 方法与对象“_global”相交失败

runtime error 50290 method intersect of object '_global' failed

提问人:Dani 提问时间:11/12/2023 最后编辑:FunThomasDani 更新时间:11/12/2023 访问量:64

问:

我是 VBA 编程的新手,并且正在努力遵循以下代码,该代码的目的是具有一个具有多个选择的下拉列表,该列表仅限于某些单元格。 问题是,当只打开带有VBA的文件时,VBA工作正常。 当我并行打开另一个 excel 文件并尝试使用下拉列表时,我收到错误说明:运行时错误 50290 方法与对象“_global”相交失败(错误出现在 If Not Intersect(Target, ActiveSheet.Range(“Mehrfachauswahl”)) Is Nothing Then 中) 我已经搜索了类似的情况,但没有找到合适的解决方案。 代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim OldVal As String
    Dim NewVal As String
    
    ' If more than 1 cell is being changed
    If Target.Count > 1 Then Exit Sub
    If Target.Value = "" Then Exit Sub
    
    If Not Intersect(Target, ActiveSheet.Range("Mehrfachauswahl")) Is Nothing Then
    
        ' Turn off events so our changes don't trigger this event again
        Application.EnableEvents = False
        
        NewVal = Target.Value
        
        ' If there's nothing to undo this will cause an error
        On Error Resume Next
        Application.Undo
        On Error GoTo 0
        
        OldVal = Target.Value
        
        ' If selection is already in the cell we want to remove it
        If InStr(OldVal, NewVal) Then
        
            'If there's a comma in the cell, there's more than one word in the cell
            If InStr(OldVal, ",") Then
                If InStr(OldVal, ", " & NewVal) Then
                    Target.Value = Replace(OldVal, ", " & NewVal, "")
                Else
                    Target.Value = Replace(OldVal, NewVal & ", ", "")
                End If
            Else
                ' If we get to here the selection was the only thing in the cell
                Target.Value = ""
            End If
        Else
            If OldVal = "" Then
                Target.Value = NewVal
            Else
                ' Delete cell contents
                If NewVal = "" Then
                    Target.Value = ""
                Else

                    ' This IF prevents the same value appearing in the cell multiple times
                    ' If you are happy to have the same value multiple times remove this IF
                    If InStr(Target.Value, NewVal) = 0 Then
                        Target.Value = OldVal & ", " & NewVal
                    End If
                End If
            End If
        End If
        Application.EnableEvents = True   
    Else
        Exit Sub 
    End If
End Sub

我在堆栈溢出中搜索并发现了类似的问题,但是由于我仍然是初学者,我不确定代码必须如何选择“我的活动工作表”

Excel VBA 错误处理 下拉列表

评论

1赞 CDP1802 11/12/2023
尝试Me.Range("Mehrfachauswahl"))
0赞 Tim Williams 11/12/2023
在工作表事件处理程序中,应用于引用工作表。即使工作表未处于活动状态,也可以触发事件。Me
0赞 Dani 11/12/2023
我已经尝试过 Me.Range(“Mehrfachauswahl”)),但仍然有相同的错误说明
0赞 CDP1802 11/13/2023
将此添加为 sub 中的第一行MsgBox "Target=" & Target.Parent.Name & " Me=" & Me.Name & " ActiveSheet=" & ActiveSheet.Name

答: 暂无答案