数据验证从非下拉列表单元格中输入的文本中选择多个项目错误消息

时间:2014-07-23 18:21:57

标签: excel vba excel-vba

我正在尝试生成一个代码,用户可以从下拉菜单(由原始单元格中的逗号分隔)中的多个项目,然后通过再次选择相同的项目来删除它们。这仅适用于工作簿中的一列,其他列是用户将在文本中输入的常规列。我遇到了一个问题,因为我所拥有的代码(见下文)适用于第一列,但是当用户试图将任何信息输入到同一工作表上其他列的其他单元格中时,运行时错误1004应用程序已定义或对象弹出定义的错误。当我按下debug时,它突出显示If Target.Validation.Type = 3然后。我从Contextures Inc复制了这段代码,当我点击测试电子表格中的外部单元格时遇到同样的问题。

非常感谢任何帮助!

Option Explicit
' Developed by Contextures Inc.
' www.contextures.com
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
Dim strVal As String
Dim i As Long
Dim lCount As Long
Dim Ar As Variant

If Target.Count > 1 Then GoTo exitHandler

If Target.Validation.Type = 3 Then
    Application.EnableEvents = False
    newVal = Target.Value
    Application.Undo
    oldVal = Target.Value
    Target.Value = newVal
    If Target.Column = 9 Then
        If oldVal = "" Then
            'do nothing
        Else
            If newVal = "" Then
                'do nothing
            Else
                On Error Resume Next
                Ar = Split(oldVal, ", ")
                strVal = ""
                For i = LBound(Ar) To UBound(Ar)
                    Debug.Print strVal
                    Debug.Print CStr(Ar(i))
                    If newVal = CStr(Ar(i)) Then
                        'do not include this item
                        strVal = strVal
                        lCount = 1
                    Else
                        strVal = strVal & CStr(Ar(i)) & ", "
                    End If
                Next i
                If lCount > 0 Then
                    Target.Value = Left(strVal, Len(strVal) - 2)
                Else
                    Target.Value = strVal & newVal
                End If
            End If
        End If
    End If
End If

exitHandler:
  Application.EnableEvents = True
End Sub

1 个答案:

答案 0 :(得分:0)

If Target.Count > 1 Then GoTo exitHandler之前添加这些行:

Set Target  = Application.Intersect(Target, Me.Columns(9))
If Target Is Nothing Then Exit Sub

这会将范围Target仅限制为第9列中的单元格

然后你可以删除这个测试:

If Target.Column = 9 Then

End If