数据validation允许多个条目

为了让用户在数据validation范围内插入多个条目,我已经写下了下面的行。 因此,如果下拉列表包含元素: x1, x2, x3, .., xn ,那么对于范围内的任何单元格,可以先select并插入x1值,然后在同一单元格中select并插入x3结果是: x1, x3等等。 问题是,当用户希望删除其中的一个值,他会得到一个Excel错误,说the user has restricted the values for this cell 。 因此,他必须删除单元格的全部内容,然后再次select他想要的值。 你可以帮助改善呢?

这里是代码:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim rngDV As Range Dim oldVal As String Dim newVal As String If Target.count > 1 Then GoTo exitHandler On Error Resume Next Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation) On Error GoTo exitHandler If rngDV Is Nothing Then GoTo exitHandler If Intersect(Target, rngDV) Is Nothing Then 'Column 7 is the one to which is the code is applied ElseIf Target.Column = 7 Then Application.EnableEvents = False newVal = Target.Value Application.Undo oldVal = Target.Value Target.Value = newVal If oldVal = "" Then Else If newVal = "" Then Else Target.Value = oldVal _ & ", " & newVal End If End If End If exitHandler: Application.EnableEvents = True End Sub 

通过VBA违反validation是可能的,这就是为什么你的代码工作在第一位。 删除条目是手动操作,其中单元格内容(逗号分隔列表)正在与您的validation列表进行比较。 您可以执行以下任一操作:

  • 使用您的单元格进行validationselect项目,并将逗号分隔的select写入不同的单元格。

  • 编写单元格的编辑function – 这样编辑的结果将通过VBA再次写入单元格。

  • 将列表(以及所有可能的删除结果添加到validation列表中(虽然非常混乱)

尝试下面

 Private Sub Worksheet_Change(ByVal Target As Range) Dim rngDV As Range Dim oldVal As String Dim newVal As String If Target.Count > 1 Then GoTo exitHandler On Error Resume Next Set rngDV = Range("G:G") On Error GoTo exitHandler If rngDV Is Nothing Then GoTo exitHandler If Intersect(Target, rngDV) Is Nothing Then ElseIf Target.Column = 7 Then Application.EnableEvents = False newVal = Target.Value Application.Undo oldVal = Target.Value Target.Value = newVal If oldVal = "" Then Else If newVal = "" Then Else Target.Value = oldVal & ", " & newVal End If End If End If exitHandler: Application.EnableEvents = True End Sub