excel 同一单元格内的数据验证多选,以逗号分隔

excel data validation multiple selection within the same celle separated by comma

我有一个 excel 电子表格,我需要从列表中插入数据验证,到目前为止没有问题,但我需要能够 select 多个条目而不覆盖以前的条目正常的数据验证所以最终结果是这样的:

List Data Validation Result
Mango Apple, Mango, Pixel
Iphone Pixel, Apple
Pixel
Apple Apple, Mango
Mango Apple, Mango, Pixel
Iphone Pixel, Apple
Pixel

我在网上找到了一个 VBA 代码,可以插入我的电子表格中,无需重复即可获得多个 selection:

Private Sub Worksheet_Change(ByVal Target As Range)
'UpdatebyExtendoffice20180510
    Dim I As Integer
    Dim xRgVal As Range
    Dim xStrNew As String
    Dim xStrOld As String
    Dim xFlag As Boolean
    Dim xArr
    On Error Resume Next
    Set xRgVal = Cells.SpecialCells(xlCellTypeAllValidation)
    If (Target.Count > 1) Or (xRgVal Is Nothing) Then Exit Sub
    If Intersect(Target, xRgVal) Is Nothing Then Exit Sub
    Application.EnableEvents = False
    xFlag = True
    xStrNew = " " & Target.Value & ","
    Application.Undo
    xStrOld = Target.Value
    If InStr(1, xStrOld, xStrNew) = 0 Then
        xStrNew = xStrNew & xStrOld & ""
    Else
        xStrNew = xStrOld
    End If
    Target.Value = xStrNew
    Application.EnableEvents = True
End Sub

有点用,但我有两个问题:

  1. 我可以从我的数据中 select 多项选择,但结果是这样
List Data Validation Result
Mango Apple, Mango, Pixel,

加上最后的逗号

  1. 如果输入错误,我无法删除或清空该字段 selection,我需要对该单元格使用擦除所有功能,然后使用下拉功能重新扩展数据验证字段到目前为止未完成的空单元格

我不熟悉 VBA,所以非常感谢您的帮助。

我主要使用 R 并且 SQL 这是我需要为我办公室的另一个人做的任务,他将要使用这个电子表格并且需要以最低的难度使用这个功能。

有什么建议吗?

我修改了代码,仅在确实需要将 2 个字符串连接在一起时才添加 space 和逗号。因此,在还选择了第二个值之前,第一个值没有附加逗号。

我还修改了它以允许清除单元格。按 Delete 键现在可以正确地允许用户清除单元格。

Private Sub Worksheet_Change(ByVal Target As Range)
'UpdatebyExtendoffice20180510
    Dim I As Integer
    Dim xRgVal As Range
    Dim xStrNew As String
    Dim xStrOld As String
    Dim xFlag As Boolean
    Dim xArr
    On Error Resume Next
    Set xRgVal = Cells.SpecialCells(xlCellTypeAllValidation)
    If (Target.Count > 1) Or (xRgVal Is Nothing) Then Exit Sub
    If Intersect(Target, xRgVal) Is Nothing Then Exit Sub
    Application.EnableEvents = False
    xFlag = True
    xStrNew = Target.Value
    Application.Undo
    xStrOld = Target.Value
    If xStrNew <> "" Then
        If InStr(1, xStrOld, xStrNew) = 0 Then
            xStrNew = xStrNew & IIf(xStrOld <> "", ", " & xStrOld, "")
        Else
            xStrNew = xStrOld
        End If
    End If
    Target.Value = xStrNew
    Application.EnableEvents = True
End Sub

我留下了它,以防它被用在没有复制到这个 post 的代码中,但是 xArrI 被声明但没有被使用。 xFlag 已声明并设置 True 但未在任何表达式中使用。