excel - VBA清除下拉列表中的内容

标签 excel vba dropdown

我创建了一个下拉列表,每次您从下拉列表中选择新内容时,它都会添加到单元格中已有的内容中。问题是,我正在尝试找到一种方法来清除它,但我认为我的顺序错误。代码如下:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
Dim lUsed As Long
If Target.Count > 1 Then GoTo exitHandler

On Error Resume Next
Set rngDV = Worksheets("Contact Log").Range("AE:AE,AI:AI,AM:AM,AQ:AQ,AU:AU,AY:AY,BC:BC,BG:BG,BK:BK,BO:BO,BS:BS,BW:BW,CA:CA,CE:CE,CI:CI")

On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler

If Intersect(Target, rngDV) Is Nothing Then
   'do nothing
Else
  Application.EnableEvents = False
  newVal = Target.Value
  Application.Undo
  oldVal = Target.Value
  Target.Value = newVal

  If oldVal = "" Then
    'do nothing
  Else
    If newVal = "" Then
      'do nothing
    Else
      lUsed = InStr(1, oldVal, newVal)
      If lUsed > 0 Then
        If newVal = "CLEAR" Then
          Selection.ClearContents
        ElseIf Right(oldVal, Len(newVal)) = newVal Then
          Target.Value = Left(oldVal, Len(oldVal) - Len(newVal) - 2)
        Else
           Target.Value = Replace(oldVal, newVal & ", ", "")
        End If
      Else
        Target.Value = oldVal & ", " & newVal
      End If
    End If
  End If
End If

exitHandler:
  Application.EnableEvents = True
End Sub

我遇到的问题是,有时,如果我从下拉菜单中选择“清除”,它会将其添加到列表中,而不是清除单元格的内容。发生这种情况时,再次选择“清除”将成功清除单元格内容。

希望这是有道理的,如果您需要我,我会澄清。发生此问题是因为我的 If 语句的顺序错误吗?

感谢您抽出时间!祝你有美好的一天!

最佳答案

在将内容复制到单元格中之前先清除内容:

    If oldVal = "" Then
      'do nothing
      Else
      If newVal = "" Then
      'do nothing
      Else
        If newVal = "CLEAR" Then
          Selection.ClearContents
          GoTo exitHandler
        end if
        .....

关于excel - VBA清除下拉列表中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188492/

相关文章:

javascript - 如何从下拉菜单 Angular 加载模板

forms - Laravel:创建具有关系的记录时,无法将外键插入表中

html - 修复了底部导航栏下拉菜单在较小屏幕上下拉到导航栏的问题

excel - 将链接图像转换为嵌入图像

excel - vlookup 可以使用通配符吗?

arrays - 当我尝试将元素放入单元格时,为什么我的分割数组会抛出错误?

class - 类模块的子对象在 vba for excel 中不起作用

vba - 突出显示行直到特定列

excel - 从单元格中删除所有图像,除了 vba 中的最后一个

excel - 如何使用 Matlab 或 Excel 从两个表中获取行的交集?