Home  >  Article  >  Topics  >  How to implement drop-down box check in Excel

How to implement drop-down box check in Excel

藏色散人
藏色散人Original
2020-02-10 09:28:1414782browse

How to implement drop-down box check in Excel

#How to implement drop-down box check in excel?

EXCEL select the drop-down box to realize the check

Step 1: Create a new excel and set the data validity [Select X column--data--valid Sex】

How to implement drop-down box check in Excel

Step 2: Development tools--view code--copy the code and save it

How to implement drop-down box check in Excel

The code is as follows:

Private Sub Worksheet_Change(ByVal Target As Range)
' Developed by Contextures Inc.
' www.contextures.com
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
If Target.Count > 1 Then GoTo exitHandler
 
On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
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 Target.Column = 7 Then '这里规定好哪一列的数据有效性是多选的,A列是第1列,依次类推,如3就是C列,7就是G列
    If oldVal = "" Then
      'do nothing
      Else
      If newVal = "" Then
      'do nothing
      Else
        If InStr(1, oldVal, newVal) <> 0 Then  &#39;重复选择视同删除
          If InStr(1, oldVal, newVal) + Len(newVal) - 1 = Len(oldVal) Then &#39;最后一个选项重复
            Target.Value = Left(oldVal, Len(oldVal) - Len(newVal) - 1)
          Else
            Target.Value = Replace(oldVal, newVal & ",", "") &#39;不是最后一个选项重复的时候处理逗号
          End If
        Else &#39;不是重复选项就视同增加选项
        Target.Value = oldVal & "," & newVal
&#39;      NOTE: you can use a line break,
&#39;      instead of a comma
&#39;      Target.Value = oldVal _
&#39;        & Chr(10) & newVal
        End If
      End If
    End If
  End If
End If
 
exitHandler:
  Application.EnableEvents = True
End Sub

For more Excel-related technical articles, please visit the Excel Basic Tutorial column!

The above is the detailed content of How to implement drop-down box check in Excel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn