我有一個 excel 電子表格,我需要從串列中插入資料驗證,到目前為止還不是問題,但我需要能夠選擇多個條目而不會像普通資料驗證那樣覆寫以前的條目,因此最終結果是這樣的:
| 串列 | 資料驗證結果 |
|---|---|
| 芒果 | 蘋果、芒果、像素 |
| 蘋果手機 | 像素,蘋果 |
| 像素 | |
| 蘋果 | 蘋果、芒果 |
| 芒果 | 蘋果、芒果、像素 |
| 蘋果手機 | 像素,蘋果 |
| 像素 |
我在網上找到了一個 VBA 代碼,可以插入到我的電子表格中,以便在不重復的情況下進行多項選擇:
Private Sub Worksheet_Change(ByVal Target As Range)
'UpdatebyExtendoffice20180510
Dim I As Integer
Dim xRgVal As Range
Dim xStrNew As String
Dim xStrOld As String
Dim xFlag As Boolean
Dim xArr
On Error Resume Next
Set xRgVal = Cells.SpecialCells(xlCellTypeAllValidation)
If (Target.Count > 1) Or (xRgVal Is Nothing) Then Exit Sub
If Intersect(Target, xRgVal) Is Nothing Then Exit Sub
Application.EnableEvents = False
xFlag = True
xStrNew = " " & Target.Value & ","
Application.Undo
xStrOld = Target.Value
If InStr(1, xStrOld, xStrNew) = 0 Then
xStrNew = xStrNew & xStrOld & ""
Else
xStrNew = xStrOld
End If
Target.Value = xStrNew
Application.EnableEvents = True
End Sub
它有點作業,但我有兩個問題:
- 我可以從我的資料中選擇多個選項,但結果是這樣的
| 串列 | 資料驗證結果 |
|---|---|
| 芒果 | 蘋果、芒果、像素、 |
最后一個逗號
- 如果我做出錯誤的選擇,我無法洗掉或清空該欄位,我需要在該單元格上使用擦除所有功能,然后使用下拉功能從迄今為止尚未完成的空單元格中重新擴展資料驗證欄位
我不熟悉 VBA,所以任何幫助表示贊賞。
我主要使用 R 和 SQL,這是我需要為辦公室中將使用此電子表格并需要以最低難度使用此功能的另一個人執行的任務。
有什么建議?
uj5u.com熱心網友回復:
我修改了代碼,僅在實際需要將 2 個字串連接在一起時才添加空格和逗號。因此,在選擇第二個值之前,第一個值不會附加逗號。
我還修改了它以允許清除單元格。按 Delete 現在將正確允許用戶清除單元格。
Private Sub Worksheet_Change(ByVal Target As Range)
'UpdatebyExtendoffice20180510
Dim I As Integer
Dim xRgVal As Range
Dim xStrNew As String
Dim xStrOld As String
Dim xFlag As Boolean
Dim xArr
On Error Resume Next
Set xRgVal = Cells.SpecialCells(xlCellTypeAllValidation)
If (Target.Count > 1) Or (xRgVal Is Nothing) Then Exit Sub
If Intersect(Target, xRgVal) Is Nothing Then Exit Sub
Application.EnableEvents = False
xFlag = True
xStrNew = Target.Value
Application.Undo
xStrOld = Target.Value
If xStrNew <> "" Then
If InStr(1, xStrOld, xStrNew) = 0 Then
xStrNew = xStrNew & IIf(xStrOld <> "", ", " & xStrOld, "")
Else
xStrNew = xStrOld
End If
End If
Target.Value = xStrNew
Application.EnableEvents = True
End Sub
我留下了它,以防它被用在沒有復制到這篇文章的代碼中,但是xArr&I被宣告但沒有被使用。xFlag已宣告并設定True但未在任何運算式中使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372749.html
下一篇:使用VBA將資料拆分為多個作業表
