我正在尝试从下拉菜单中进行计算。 这是我的下拉菜单的外观。 类别
这些是与我的下拉菜单相关的值。 类别类别值
我添加了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
答案 0 :(得分:0)
对于汇总部分,我会做类似的事情。我有参考表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
答案 1 :(得分:0)
您可以简单地使用此功能,而不用在VBA中进行编码。
=SUMPRODUCT(ISNUMBER(SEARCH(Sheet2!A1:I4;Sheet1!A2))*Sheet2!B1:B4)