我有以下列
A | B
Name | Value
One | 1
Two | 2
Three | 3
在 C 列中,我希望有一个验证下拉列表,显示名称和值的串联(即 One - 1、Two - 2 等)。当用户做出选择(即 Two - 2)时,只有值列中的数据会填充单元格(即 2)。
我怎样才能完成这一壮举?
答案1
使用如下数据:
将以下 VBA 宏放入标准模块并运行它:
Sub DV_Maker()
Dim i As Long
Dim s As String
For i = 2 To 4
s = s & "," & Cells(i, 1) & " - " & Cells(i, 2)
Next i
s = Mid(s, 2)
With Range("C2:C4").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=s
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = False
End With
End Sub
它将设置单元格的数据验证C2,C3, 和C4。然后将此事件宏放置在工作表代码区域中:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Range("S2:C4")
If Intersect(Target, rng) Is Nothing Then Exit Sub
Application.EnableEvents = False
Target.Value = Split(Target.Value, " - ")(1)
Application.EnableEvents = True
End Sub
输入数据后,事件宏将从单元格中删除文本。