我創建了一個下拉列表,每次從下拉列表中選擇新的內容時,它都會添加到單元格中已有的內容中。問題是,我正試圖找到一種方法來清除它,並且我認爲我的訂購錯誤。下面的代碼:下拉列表中的VBA清除內容
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語句的順序錯誤嗎?
感謝您花時間!祝你有美好的一天!