從 Excel 中的多項選擇下拉清單中檢索值

從 Excel 中的多項選擇下拉清單中檢索值

我正在嘗試從下拉式選單中進行計算。我的 Excel 工作表 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

答案1

=SUM(IF(ISERR(FIND(Sheet2!$I$2:$I$5;A1;1));0;Sheet2!$J$2:$J$5))

這一定有效,但它不是一個常規公式。它是一個大批公式。要使數組公式起作用,您需要輸入它不是與,而是使用+ +Enter的組合。CtrlShiftEnter

另外,將 變更A1為您的實際下拉儲存格。

例子

相關內容