我正在尝试从下拉菜单中进行计算。我的 Excel 中的 Sheet 1 中有以下下拉菜单。
## Category ##
### AAA ###
### BBB ###
### CCC ###
### DDD ###
在工作表 2 中,我有此下拉菜单的对应值。
## Category Category Value##
### AAA 1###
### BBB 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