excel - 从 excel 中的多项选择下拉列表中检索值
问题描述
我正在尝试从我的下拉菜单中进行计算。这就是我的下拉菜单的样子。类别
- AAA
- BBB
- CCC
- DDD
这些是与我的下拉菜单关联的值。类别 类别值
- AAA 1
- 血脑屏障 2
- CCC 3
- DDD 4
我为多选添加了 VBA 代码,还添加了简单的 Vlookup 公式来检索类别的值。
=VLOOKUP(E2;Sheet2!I2:J5;2;)
使用 VBA 代码,我可以选择所有三个类别,并在以后删除所选类别。但我无法检索所选类别的总和。例如,如果客户选择 AAA 和 CCC 类别,他/她应该能够看到总和为 4。此外,如果客户首先选择所有三个类别,然后删除其中一个类别,那么总和也应该得到更新。我不知道如何更新我的 Vlookup 公式以获得总和。
这是我用于多项选择的 VBA 代码。
Private Sub Worksheet_Change(ByVal Target As Range)
'Updated: 2016/4/12
Dim xRng As Range
Dim xValue1 As String
Dim xValue2 As String
If Target.Count > 1 Then Exit Sub
On Error Resume Next
Set xRng = Cells.SpecialCells(xlCellTypeAllValidation)
If xRng Is Nothing Then Exit Sub
Application.EnableEvents = False
If Not Application.Intersect(Target, xRng) Is Nothing Then
xValue2 = Target.Value
Application.Undo
xValue1 = Target.Value
Target.Value = xValue2
If xValue1 <> "" Then
If xValue2 <> "" Then
' If xValue1 = xValue2 Or _
' InStr(1, xValue1, ", " & xValue2) Or _
InStr(1, xValue1, xValue2 & ",") Then
If InStr(1, xValue1, xValue2 & ",") > 0 Then
xValue1 = Replace(xValue1, xValue2 & ", ", "") ' If it's in the middle with comma
Target.Value = xValue1
GoTo jumpOut
End If
If InStr(1, xValue1, ", " & xValue2) > 0 Then
xValue1 = Replace(xValue1, ", " & xValue2, "") ' If it's at the end with a comma in front of it
Target.Value = xValue1
GoTo jumpOut
End If
If xValue1 = xValue2 Then ' If it is the only item in string
xValue1 = ""
Target.Value = xValue1
GoTo jumpOut
End If
Target.Value = xValue1 & ", " & xValue2
End If
jumpOut:
End If
End If
Application.EnableEvents = True
End Sub
解决方案
我会为求和部分做类似的事情。我有我的参考表 A1:B4。我打电话给使用Get_Sum("A,C,D")
Function Get_Sum(strInput As String) As Double
Dim a() As String
Dim v As Variant
Dim r As Excel.Range
Dim l As Long
a = Split(strInput, ",")
Set r = Range("a1:b4")
Get_Sum = 0
For Each v In a
l = Application.WorksheetFunction.Match(v, r.Columns(1), 0)
Get_Sum = Get_Sum + r.Cells(l, 2)
Next v
Set r = Nothing
Erase a
End Function
像这样打电话
Private Sub Worksheet_Change(ByVal Target As Range)
' Where A5 is the validated cell and B5 is the sum result
If Target = Range("a5") Then
Range("b5").value = Get_Sum (Target.Value)
End If
End Sub
推荐阅读
- python - 运行 setup.py 时以 '\xff' 开头的非 UTF-8 代码
- android - 错误:模块“playerlib”:找不到平台“android-28”
- qt - 使用 CMake 编译 QTCreator 和 VisualStudio 代码
- mysql - 如何用小数计算 MySQL 中的百分位数?
- c# - 如果在选择新的 linq 中结果为 < 0
- node.js - 如何在 MVC 架构中创建松散耦合的服务?
- reactjs - 如何在非反应 3rd 方 html 中呈现多个反应组件
- selenium - 使用 selenium-chrome-driver 4.0.0-alpha-5 并且我收到此错误:“此版本的 ChromeDriver 仅支持 Chrome 版本 81”
- java - 持续的 React Native 问题:未设置 JAVA_HOME
- javascript - 如何验证嵌套和有条件可选的 Yup 模式