|
- Private Sub Worksheet_Change(ByVal Target As Range)
- Dim rngDV As Range
- Dim oldVal As String
- Dim newVal As String
- Dim strVal As String
- Dim i As Integer
- Set rngDV = Me.Range("D5")
- If Intersect(Target, rngDV) Is Nothing Then Exit Sub
- If rngDV.Value = "" Then Exit Sub
- Application.EnableEvents = False
- newVal = Target.Value
- Application.Undo
- oldVal = Target.Value
- Target.Value = newVal
- If oldVal = "" Then
- GoTo exitHandler
- End If
- On Error Resume Next
- If InStr(1, oldVal, newVal) = 0 Then
- strVal = oldVal & "|" & newVal
- Else
- i = InStr(1, oldVal, newVal)
- If i = 1 Then
- strVal = Right(oldVal, Len(oldVal) - Len(newVal) - 1)
- Else
- strVal = Left(oldVal, i - 1) & Mid(oldVal, i + Len(newVal) + 1)
- End If
- End If
- Target.Value = Trim(strVal)
- exitHandler:
- Application.EnableEvents = True
- End Sub
- Sub SetupDataValidation()
- Dim ws As Worksheet
- Dim rng As Range
- Dim dv As Validation
- Set ws = ActiveSheet
- Set rng = ws.Range("D5")
- rng.Validation.Delete
- Set dv = rng.Validation
- With dv
- .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="苹果,香蕉,橙子,葡萄,西瓜"
- .IgnoreBlank = True
- .InCellDropdown = True
- .ShowInput = True
- .ShowError = True
- End With
- End Sub
复制代码 |
|