vba - 使用宏在 Excel 中进行多选,如何取消选择选择

标签 vba excel

我需要使用 MultiSelect 下拉菜单创建启用宏的 excelsheet。

  • 用户选择下拉列表之一,然后用逗号(,)分隔将值附加到单元格中。
  • 如果用户再次选择已选择的值,则应将其从列表中删除。

  • 通过以下代码,我能够实现它的第一部分,但无法实现第二部分。
        Private Sub Worksheet_Change(ByVal Target As Range)
        Dim Oldvalue As String
        Dim Newvalue As String
        Application.EnableEvents = True
        On Error GoTo Exitsub
        If Target.Address = "$D$2" Then
          If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
            GoTo Exitsub
          Else: If Target.Value = "" Then GoTo Exitsub Else
            Application.EnableEvents = False
            Newvalue = Target.Value
            Application.Undo
            Oldvalue = Target.Value
              If Oldvalue = "" Then
                Target.Value = Newvalue
              Else
                If InStr(1, Oldvalue, Newvalue) = 0 Then
                    Target.Value = Oldvalue & ", " & Newvalue
              Else:
                Target.Value = Oldvalue
              End If
            End If
          End If
        End If
        Application.EnableEvents = True
        Exitsub:
        Application.EnableEvents = True
        End Sub
    

    如何实现第 2 部分?请建议。

    最佳答案

    你可以替代:

    If InStr(1, Oldvalue, Newvalue) = 0 Then
        Target.Value = Oldvalue & ", " & Newvalue
    

    和:
        If InStr(1, Oldvalue, Newvalue) = 0 Then
            Target.Value = Oldvalue & ", " & Newvalue
        Else
            Target.Value = Replace(Target.Value, Newvalue, "") ' remove value from list
            If Right(Target.Value, 1) = "," Then 'if removed value was the last value of the list
                Target.Value = Left(Target.Value, Len(Target.Value) - 1) ' remove ending comma
            ElseIf Left(Target.Value, 1) = "," Then 'if removed value was the first value of the list
                Target.Value = Mid(Target.Value, 2) ' remove leading comma
            Else ' removed value was in the middle of the list
                Target.Value = Replace(Target.Value, ",,", "") ' remove double comma
            End If
        End If
    

    关于vba - 使用宏在 Excel 中进行多选,如何取消选择选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539722/

    相关文章:

    vba - 在Excel中使用VBA查找事件单元格的列标题名称

    vba - 在多个工作簿中使用相同的热键

    sql-server - 测试 SQL Server 连接

    c# - 是否可以使用 C# 在 Excel 中执行撤消/重做?

    excel - (Power) Pivot - 显示真/假并同时计算

    perl - 从序列中删除给定范围的字母

    ms-access - Access.Application.Eval() 的奇怪行为

    python - 将复数的 Pandas 数据框导出到excel

    excel - 验证还是不验证?

    vba - 在excel电子表格之间复制信息的代码