在一個系統(tǒng)剛上線時,需要把以前的數(shù)據(jù)導(dǎo)入系統(tǒng),方便使用與管理,程序不是萬能的,導(dǎo)入表格要符合系統(tǒng)要求的規(guī)則才能順利地導(dǎo)入。在整理龐大而又繁瑣的數(shù)據(jù)時,為了減少系統(tǒng)報錯的概率,可以事先對excel的表格格式做處理。文章里要說的是一個不常用到的一個小技巧-----下拉框多選。我問了百度,找到了一些方法,把最簡單最快捷的方法給出來,像我一樣不懂宏不懂代碼的小伙伴可以看下。
首先在某列利用數(shù)據(jù)有效性-建立下拉菜單表。數(shù)據(jù)-->數(shù)據(jù)有效性-->數(shù)據(jù)有效性,“允許”選擇“序列”,然后把需要選擇的內(nèi)容輸入到來源里,中間用英文逗號“,”隔開。下拉框單選便成了。


然后在下拉表所打開的sheet中(如sheet1),鼠標(biāo)右擊下面的工作表,選擇“查看代碼”,就可打開VBA編輯界面。復(fù)制下方的代碼,并將其中一行的 ? If Target.Column = 7 Then ? ?中的7修改為下拉數(shù)據(jù)表所在的列數(shù),搞定。第幾列便是數(shù)字幾,A是1,B是2,以此類推。

表格中兩個選項間用中文逗號、英文逗號、頓號、橫杠等等符號隔開,把下面兩句代碼中雙引號間的符號改為想要的符號即可,注意二者要保持一致。

代碼:
Private Sub Worksheet_Change(ByVal Target As Range)
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?
? ? If oldVal = "" Then
? ? ? 'do nothing
? ? ? Else
? ? ? If newVal = "" Then
? ? ? 'do nothing
? ? ? Else
? ? ? ? If InStr(1, oldVal, newVal) <> 0 Then ?
? ? ? ? ? If InStr(1, oldVal, newVal) + Len(newVal) - 1 = Len(oldVal) Then?
? ? ? ? ? ? Target.Value = Left(oldVal, Len(oldVal) - Len(newVal) - 1)
? ? ? ? ? Else
? ? ? ? ? ? Target.Value = Replace(oldVal, newVal & ",", "")
? ? ? ? ? End If
? ? ? ? Else?
? ? ? ? Target.Value = oldVal & "," & newVal
'? ? ? NOTE: you can use a line break,
'? ? ? instead of a comma
'? ? ? Target.Value = oldVal _
'? ? ? ? & Chr(10) & newVal
? ? ? ? End If
? ? ? End If
? ? End If
? End If
End If
exitHandler:
? Application.EnableEvents = True
End Sub
代碼來源:知乎
鏈接:https://www.zhihu.com/question/20484204/answer/142569580
說明:代碼中 ' 后面的內(nèi)容為說明文字,可以刪除,不影響代碼的執(zhí)行,放在excel里會變?yōu)榫G色,這些只是說明。當(dāng)然也可以加 ' ,然后加入自己要說明的東西。

額外說明:
excel保存時會提示宏無法保存,這個問題目前還沒研究出來,慶幸本次的設(shè)計只是給自己公司內(nèi)部人用的,所以只能復(fù)制代碼給他們,讓他們自己復(fù)制一遍了。

如果哪位大神有解決辦法,望賜教~~
補(bǔ)充:有朋友問到,上面的代碼只能實現(xiàn)一列的多選,那如果我有兩列或更多列要多選,該怎么實現(xiàn)呢?
這個很容易實現(xiàn),加or,
If Target.Column = 7 or?arget.Column = 8?Then
即可實現(xiàn)很7列與第8列同時多選。